forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackAsLinkedList.java
More file actions
56 lines (42 loc) · 1.12 KB
/
StackAsLinkedList.java
File metadata and controls
56 lines (42 loc) · 1.12 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
// Time Complexity: O(1)
// Space Complexity: O(n)
public class StackAsLinkedList {
StackNode root;
static class StackNode {
int data;
StackNode next;
StackNode(int data) {
this.data = data;
this.next = null;
}
}
public boolean isEmpty() {
return (root == null);
}
public void push(int data) {
StackNode newNode = new StackNode(data);
newNode.next = root;
root = newNode;
}
public int pop() {
if (root == null) {
System.out.println("Stack Underflow");
return 0;
}
int popped = root.data;
root = root.next;
return popped;
}
public int peek() {
return root.data;
}
// Driver code
public static void main(String[] args) {
Excercise_2 sll = new Excercise_2();
sll.push(10);
sll.push(20);
sll.push(30);
System.out.println(sll.pop() + " popped from stack");
System.out.println("Top element is " + sll.peek());
}
}