Skip to content

Instantly share code, notes, and snippets.

@SIRHAMY
Created May 19, 2016 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SIRHAMY/2cc481beeff569283d98f03a1d6982cb to your computer and use it in GitHub Desktop.
Save SIRHAMY/2cc481beeff569283d98f03a1d6982cb to your computer and use it in GitHub Desktop.
Simply Singly Linked List reverser in Java.
public class Reverser {
public Node reverseSLL(Node head) {
//To reverse:
//A -> B -> C
//A <- B <- C
//Save B's pointer to C
//Set B's pointer to A/where we came from
//Save pointer to B
Node prev = null;
Node next = null;
Node curr = head;
while(curr != null) {
next = curr.getNext();
curr.setNext(prev);
prev = curr;
curr = next;
}
return prev;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment