Saturday, 15 August 2015

algorithm - How to reverse a linkedList iteratively, understanding the code I found online -



algorithm - How to reverse a linkedList iteratively, understanding the code I found online -

i trying code different interview questions. classic question reversing singly linked list. found code online , commented it, point swap pointers, don't happening.

public static linkedlist iterativereverse(linkedlist linkedlist) { if (linkedlist == null || linkedlist.next == null) { //we check if list empty or has 1 node , accordingly homecoming list if case homecoming linkedlist; } linkedlist prevnode, currnode, nextnode; //three pointers prevnode = null; // pointers nextnode = null; // temporary pointers swapping? currnode = linkedlist; //is node pointing head going point null? while (currnode != null) { // long haven't reached end of list nextnode = currnode.next; //here gets complicated me, don't understand happening currnode.next = prevnode; prevnode = currnode; currnode = nextnode; } homecoming prevnode; }

could please set me on right track of approaching problem?

thank you.

assume have linked list a-->b-->c , prevnode points a , currnode point b.

so nextnode = currnode.next; equivalent point nextnode c.

in order reverse linked list, need alter direction of link a-->b b-->a, , happened in:

currnode.next = prevnode;

now, job left update prevnode b , curnode c, , repeat process.

prevnode = currnode; currnode = nextnode;

algorithm linked-list swap iteration

No comments:

Post a Comment