This repository was archived by the owner on Apr 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathReverseLinkedList.java
More file actions
80 lines (52 loc) · 1.47 KB
/
ReverseLinkedList.java
File metadata and controls
80 lines (52 loc) · 1.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*-- Reversing a LinkedList using Stack --*/
import java.util.*;
public class ReverseLinkedList {
static Node reverseLinkedList(Node head) {
Stack<Integer> stack = new Stack<>();
Node n = head;
while(n!=null){
stack.push(n.data);
n = n.next;
}
Node newList = new Node(stack.pop());
Node nodesNewList = newList;
while(!stack.isEmpty()){
nodesNewList.next = new Node(stack.pop());
nodesNewList = nodesNewList.next;
}
return newList;
}
/*-- Inputs from the main method --*/
public static void main(String[] args){
Node A = new Node(5);
A.addNodeToTail(10);
A.addNodeToTail(20);
A.addNodeToTail(30);
A.addNodeToTail(35);
A.addNodeToTail(40);
A.addNodeToTail(50);
Node C = reverseLinkedList(A);
while(C!=null){
System.out.println(C.data);
C = C.next;
}
}
}
/*-- Node class Implementation --*/
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
public void addNodeToTail(int addData){
Node current = this;
while(current!=null){
if(current.next==null){
current.next = new Node(addData);
break;
}
current = current.next;
}
}
}