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
78 lines (68 loc) · 1.95 KB
/
StackAsLinkedList.java
File metadata and controls
78 lines (68 loc) · 1.95 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
// Time Complexity : O(1)
// Space Complexity : O(N)
// Did this code successfully run on Leetcode :
// Any problem you faced while coding this : N/A
class StackNode {
int data;
//Creating a doubly linked list
StackNode next;
StackNode prev;
//Implementing it through doubly linkedList.
//Creating constructors
StackNode(){
}
StackNode(int data) {
//Constructor here
this.data = data;
this.next = null;
this.prev = null;
}
StackNode(int data, StackNode next) {
//Constructor here
this.data = data;
this.next = next;
this.prev = null;
}
StackNode(int data, StackNode next,StackNode prev) {
//Constructor here
this.data = data;
this.next = next;
this.prev = prev;
}
}
public class StackAsLinkedList {
StackNode root = new StackNode();
public boolean isEmpty() {
//Write your code here for the condition if stack is empty.
if(root == null){ // comparing whether the root is null or not
return true;
}
return false;
}
public void push(int data) {
//Write code to push data to the stack.
StackNode newNode = new StackNode(data); // creating node with input data
if (this.root == null){
root.data = data;
}else{
root.next = newNode;
newNode.prev = root;
root = root.next;
}
}
public int pop() {
//If Stack Empty Return 0 and print "Stack Underflow"
if(root == null){
System.out.println("Stack Underflow");
return 0;
}
int x = root.data;
root = root.prev;
root.next = null;
return x;
}
public int peek() {
//Write code to just return the topmost element without removing it.
return root.data;
}
}