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
90 lines (75 loc) · 2.13 KB
/
Exercise_2.java
File metadata and controls
90 lines (75 loc) · 2.13 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
/**
* Time complexity = O(n)
* Space complexity = O(n)
*/
class StackAsLinkedList {
StackNode root;
static class StackNode {
int data;
StackNode next;
StackNode(int data)
{
//Constructor here
this.data = data;
}
}
public boolean isEmpty()
{
//Write your code here for the condition if stack is empty.
return root == null;
}
public void push(int data)
{
StackNode newNode = new StackNode(data);
// If the Linked List is empty,
// then make the new node as head
if(root == null) root = newNode;
else {
StackNode currentNode= root;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
currentNode.next = newNode;
}
}
public int pop()
{
if (root == null) return 0;
else if(root.next == null){
int data = root.data;
root = null;
return data;
}
else {
StackNode currentNode = root;
StackNode previousNode = root;
while (currentNode.next != null) {
previousNode = currentNode;
currentNode = currentNode.next;
}
int data = currentNode.data;
previousNode.next = null;
return data;
}
}
public int peek() {
if (root == null) return 0;
else {
StackNode currentNode = root;
while (currentNode.next != null) {
currentNode = currentNode.next;
}
return currentNode.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());
}
}