Java Reverse a linked list pairwise -


i trying reverse linked list pairwise i.e follows

1->2->3->4->5 changed 2->1->4->3->5 

i have been able recursively. however, getting confused while doing iteratively.

public class fastlist<item> {     private node<item> first;      private static class node<item>     {         item item;           node<item> next;     }      public void swappairwiseiterative()  // not working     {         if(first == null || first.next==null)             return;          node 1 = first, two;         first= first.next;          while ( 1 != null || one.next != null )         {             2 = one.next;             one.next = two.next;             two.next = one;             1 = one.next.next;         }     } } 

on debugging, noticed able swap 2 nodes correctly, not able assign first instance variable, points first element of list. how do ?

also, line

first= first.next; 

looks bit hacky. please suggest more natural way of doing it.

try this:

public void swappairwiseiteratively() {   if(first == null || first.next==null) return;   node 1 = first, 2 = first.next, prev = null;   first = two;   while (one != null && 2 != null) {     // previous node should point 2     if (prev != null) prev.next = two;     // node 1 should point 1 after 2     one.next = two.next;     // node 2 should point 1     two.next = one;     // getting ready next iteration     // 1 (now last node) prev node     prev = one;     // 1 prev's successor     1 = prev.next;     // 2 prev's successor's successor     if (prev.next != null) 2 = prev.next.next;     else 2 = null;   } } 

i not sure can 2 pointers instead of three. work solution above (i haven't tested should correct) , figure out if can improved. don't think line first = two can removed.

you remove condition if (prev != null) if move first pair swapping out of loop (an optimization premature in example).


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -