-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackAsLinkedList.java
82 lines (68 loc) · 1.98 KB
/
StackAsLinkedList.java
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
class Node {
int data;
Node next;
// Constructor to initialize a node
Node(int data) {
this.data = data;
this.next = null;
}
}
class StackAsLinkedList {
Node top;
// Constructor to initialize an empty stack
StackAsLinkedList() {
this.top = null;
}
// Method to check if the stack is empty
public boolean isEmpty() {
return top == null;
}
// Method to push an element to the stack
public void push(int data) {
Node newNode = new Node(data);
newNode.next = top;
top = newNode;
System.out.println(data + " pushed to stack");
}
// Method to pop an element from the stack
public int pop() {
if (isEmpty()) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
int popped = top.data;
top = top.next;
return popped;
}
// Method to peek at the top element of the stack
public int peek() {
if (isEmpty()) {
System.out.println("Stack is empty");
return Integer.MIN_VALUE;
}
return top.data;
}
// Method to print the stack elements
public void printStack() {
if (isEmpty()) {
System.out.println("Stack is empty");
return;
}
Node currentNode = top;
while (currentNode != null) {
System.out.print(currentNode.data + " ");
currentNode = currentNode.next;
}
System.out.println();
}
public static void main(String[] args) {
StackAsLinkedList stack = new StackAsLinkedList();
stack.push(10);
stack.push(20);
stack.push(30);
stack.printStack(); // Output: 30 20 10
System.out.println(stack.pop() + " popped from stack"); // Output: 30 popped from stack
stack.printStack(); // Output: 20 10
System.out.println("Top element is " + stack.peek()); // Output: Top element is 20
}
}