Question: Write a java method for a linked list: public void shift ( ) . This method will rearrange the elements of a list of integers

Write a java method for a linked list: public void shift(). This method will rearrange the elements of a list of integers by moving to the end of the list all values that are in odd-numbered positions and otherwise presern; what matters is whether the value appears in an odd index (index 1,3,5, etc.). Also, the original order of the elements of the list should otherwise be preserved. You may not construct any new nodes nor use any auxiliary data structures to solve this problem. You also may not change any data fields of the nodes; you MUST solve this problem by rearranging the links of the list. For example, suppose that a variable list stores the values [10,31,42,23,44,75,86]. The call of list.shift() should rearrange the list to store [10,42,44,86,31,23,75].
There were something wrong with my codes:
public void shift(){
//we are storing second node in prev because we wrote diffrent logic for first node in first if condition
ListNode previous = front.next;
for (int i=1; i<=this.size(); i++){
if (i ==1){// logic for first node
ListNode temp_node = front; // storing first node
ListNode current = front;
front = current.next;
while (current.next != null){
current = current.next; // going to add node of list
}
temp_node.next = null; // before adding node make next of node null because it will be added at last now
current.next = temp_node; // adding first node at last
}
else if (i %2==1){// logic for nodes other than first node
ListNode current = front;
ListNode temp_node = previous.next; // this is the odd number node which we will add at last
previous.next = temp_node.next; // now linking the prev node to the next of odd index node.
previous = temp_node.next; // now storing the prev node as the next of odd index node which we will add at last
while (current.next != null){
current = current.next; // going to last node of list
}
temp_node.next = null; // making next of node as null before being added at last
current.next = temp_node; // now adding at last
}
}// end of for loop
}// end shift method

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!