forked from super30admin/PreCourse-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exercise_2.java
115 lines (90 loc) · 2.96 KB
/
Exercise_2.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Java program to implement a stack using singly linked
// Time complexity = O(1) push, boolean, peak, pop all are O(1)
// Space Complexity O(n) - n is the number of items in stack
// Did this code successfully run on Leetcode :N/A
// Any problem you faced while coding this : No
// Class representing a node in the linked list
class Node {
int data;
Node next;
Node(int new_data) {
this.data = new_data;
this.next = null;
}
}
// Class to implement stack using a singly linked list
class Stack {
// Head of the linked list
Node head;
// Constructor to initialize the stack
Stack() { this.head = null; }
// Function to check if the stack is empty
boolean isEmpty() {
// If head is null, the stack is empty
return head == null;
}
// Function to push an element onto the stack
void push(int new_data) {
// Create a new node with given data
Node new_node = new Node(new_data); // initialize the node
// Check if memory allocation for the new node
// failed
if (new_node == null) {
System.out.println("\nStack Overflow");
return;
}
// Link the new node to the current top node
new_node.next = head;
// Update the top to the new node
head = new_node;
}
// Function to remove the top element from the stack
int pop() {
// Check for stack underflow
if (isEmpty()) {
System.out.println("\nStack Underflow");
return Integer.MIN_VALUE; // return a value to indicate underflow
}
else {
// Assign the current top to a temporary variable
Node temp = head;
int poppedData = temp.data;
// Update the top to the next node
head = head.next;
// Deallocate the memory of the old top node
temp = null;
return poppedData;
}
}
// Function to return the top element of the stack
int peek() {
// If stack is not empty, return the top element
if (!isEmpty())
return head.data;
else {
System.out.println("\nStack is empty");
return Integer.MIN_VALUE;
}
}
}
// Driver code
class Main {
public static void main(String[] args)
{
// Creating a stack
Stack st = new Stack();
// Push elements onto the stack
st.push(11);
st.push(22);
st.push(33);
st.push(44);
// Print top element of the stack
System.out.println("Top element is " + st.peek());
// removing two elemements from the top
System.out.println("Removing two elements...");
st.pop();
st.pop();
// Print top element of the stack
System.out.println("Top element is " + st.peek());
}
}