Skip to content

Instantly share code, notes, and snippets.

@zerobranch
Last active March 15, 2021 20:25
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 zerobranch/8635c6afb067bba540ae8cd72b3f8494 to your computer and use it in GitHub Desktop.
Save zerobranch/8635c6afb067bba540ae8cd72b3f8494 to your computer and use it in GitHub Desktop.
reverseLinkedList
public class Main {
public static void main(String[] args) {
new Main().modeMain();
}
private void modeMain() {
Node head = getNodes();
print(head);
Node reverseNode = reverseLinkedList(head);
print(reverseNode);
}
private Node reverseLinkedList(Node in) {
Node head = in;
while (in.link != null) {
Node next = in.link;
in.link = next.link;
next.link = head;
head = next;
}
return head;
}
private Node getNodes() {
Node head = new Node(1);
Node n2 = new Node(2);
Node n3 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
head.link = n2;
n2.link = n3;
n3.link = n4;
n4.link = n5;
return head;
}
private void print(Node head) {
while (head != null) {
System.out.print(head.value + " ");
head = head.link;
}
System.out.println();
}
}
class Node {
int value;
Node link;
public Node(int value) {
this.value = value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment