Last active
November 25, 2023 19:35
-
-
Save thmain/d92f693a132594e2eeb9417354f2598d to your computer and use it in GitHub Desktop.
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
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