Skip to content

Instantly share code, notes, and snippets.

@zac-xin
Created October 28, 2012 02:45
Show Gist options
  • Save zac-xin/3967248 to your computer and use it in GitHub Desktop.
Save zac-xin/3967248 to your computer and use it in GitHub Desktop.
Reverse Linked List
package Chapter2;
/*
* reverse a linked list
*/
public class ReverseList {
public static void main(String args[]){
IntNode n1, n2, n3, n4, n5, n6,n7, n8, n9;
n9 = new IntNode(10, null);
n8 = new IntNode(9, n9);
n7 = new IntNode(8, n8);
n6 = new IntNode(6, n7);
n5 = new IntNode(5, n6);
n4 = new IntNode(4, n5);
n3 = new IntNode(3, n4);
n2 = new IntNode(2, n3);
n1 = new IntNode(1, n2);
n1.printNodes();
reverse(n1);
n9.printNodes();
}
public static IntNode reverse(IntNode head){
if(head == null)
return null;
if(head.link == null)
return null;
IntNode pre = null;
IntNode current = head;
IntNode next;
while(current != null){
next = current.link;
current.link = pre;
pre = current;
current = next;
}
return pre;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment