Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active November 25, 2023 19:35
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 thmain/d92f693a132594e2eeb9417354f2598d to your computer and use it in GitHub Desktop.
Save thmain/d92f693a132594e2eeb9417354f2598d to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class ReverseLL {
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public static Node reverseList(Node head) {
Node newHead = null;
Node current = null;
Stack<Node> stack = new Stack<>();
while(head!=null){
stack.push(head);
head = head.next;
}
while(!stack.isEmpty()){
Node n = stack.pop();
if(newHead==null){
newHead = n;
current = n;
}else{
current.next = n;
current = current.next;
}
n.next=null;
}
return newHead;
}
public static void display(Node head) {
Node currNode = head;
while (currNode != null) {
System.out.print("->" + currNode.data);
currNode = currNode.next;
}
System.out.println();
}
public static void main(String[] args) {
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
System.out.println("Original List :");
display(head);
System.out.println("Reversed List :");
Node x = reverseList(head);
display(x);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment