Last active
March 15, 2021 20:25
-
-
Save zerobranch/8635c6afb067bba540ae8cd72b3f8494 to your computer and use it in GitHub Desktop.
reverseLinkedList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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