-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked list using Stack
More file actions
112 lines (99 loc) · 2.85 KB
/
Linked list using Stack
File metadata and controls
112 lines (99 loc) · 2.85 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import java.util.Stack;
public class LinkedListWithStack {
private static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
this.next = null;
}
}
private Node head;
private Stack<Node> stack;
public LinkedListWithStack() {
head = null;
stack = new Stack<>();
}
// Insertion at the beginning using stack
public void insertAtBeginning(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
newNode.next = head;
head = newNode;
}
stack.push(newNode); // Push the new node onto the stack
}
// Insertion at the end using stack
public void insertAtEnd(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
stack.push(newNode); // Push the new node onto the stack
}
// Deletion from the beginning using stack
public void deleteFromBeginning() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node nodeToDelete = head;
head = head.next;
nodeToDelete.next = null;
stack.pop(); // Pop the top node from the stack
}
// Deletion from the end using stack
public void deleteFromEnd() {
if (head == null) {
System.out.println("List is empty");
return;
}
if (head.next == null) {
head = null;
stack.pop();
return;
}
Node current = head;
Node prev = null;
while (current.next != null) {
prev = current;
current = current.next;
}
prev.next = null;
stack.pop(); // Pop the top node from the stack
}
// Utility function to print the list
public void printList() {
if (head == null) {
System.out.println("List is empty");
return;
}
Node current = head;
while (current != null) {
System.out.print(current.data + " -> ");
current = current.next;
}
System.out.println("null");
}
public static void main(String[] args) {
LinkedListWithStack ll = new LinkedListWithStack();
// Insertions
ll.insertAtBeginning(3);
ll.insertAtEnd(5);
ll.insertAtBeginning(7);
ll.printList(); // Output: 7 -> 3 -> 5 -> null
// Deletions
ll.deleteFromBeginning();
ll.printList(); // Output: 3 -> 5 -> null
ll.deleteFromEnd();
ll.printList(); // Output: 3 -> null
}
}