forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_2.java
More file actions
77 lines (60 loc) · 1.99 KB
/
Exercise_2.java
File metadata and controls
77 lines (60 loc) · 1.99 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
// Time Complexity : Push - O(1), Pop - O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : yes
// Any problem you faced while coding this : no
// Your code here along with comments explaining your approach
// 1. Use a linked list where 'top' always points to the most recently pushed node.
// 2. For push: create a new node, point its next to current top, and update top.
// 3. For pop: return the data from top and move top to top.next.
public class StackAsLinkedList {
StackNode root;
static class StackNode {
int data;
StackNode next;
StackNode(int data) {
this.data = data;
this.next = null;
}
}
// Check if stack is empty
public boolean isEmpty() {
return root == null;
}
// Push element onto the stack
public void push(int data) {
// Always insert at the beginning
StackNode new_node = new StackNode(data);
// New node should now become the root (top of stack)
new_node.next = root;
root = new_node;
}
// Pop top element
public int pop() {
// If empty
if (isEmpty()) {
System.out.println("Stack Underflow");
return 0;
}
// Store current root and move root pointer
int popped = root.data;
root = root.next;
return popped;
}
// Peek top element
public int peek() {
if (isEmpty()) {
System.out.println("Stack Underflow");
return 0;
}
return root.data;
}
// Driver code
public static void main(String[] args) {
StackAsLinkedList sll = new StackAsLinkedList();
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());
}
}