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 oddnumbered positions and otherwise presern; what matters is whether the value appears in an odd index index 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 The call of list.shift should rearrange the list to store
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; ithis.size; i
if i logic for first node
ListNode tempnode front; storing first node
ListNode current front;
front current.next;
while currentnext null
current current.next; going to add node of list
tempnode.next null; before adding node make next of node null because it will be added at last now
current.next tempnode; adding first node at last
else if i logic for nodes other than first node
ListNode current front;
ListNode tempnode previous.next; this is the odd number node which we will add at last
previous.next tempnode.next; now linking the prev node to the next of odd index node.
previous tempnode.next; now storing the prev node as the next of odd index node which we will add at last
while currentnext null
current current.next; going to last node of list
tempnode.next null; making next of node as null before being added at last
current.next tempnode; 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
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
