-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay 75 Stacck using Singly Linkedlist
More file actions
95 lines (79 loc) · 1.56 KB
/
Copy pathDay 75 Stacck using Singly Linkedlist
File metadata and controls
95 lines (79 loc) · 1.56 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
91
92
93
94
95
import static java.lang.System.exit;
class GFG {
public static void main(String[] args)
{
// create Object of Implementing class
StackUsingLinkedlist obj
= new StackUsingLinkedlist();
// insert Stack value
obj.push(11);
obj.push(22);
obj.push(33);
obj.push(44);
obj.display();
System.out.printf("\nTop element is %d\n",
obj.peek());
obj.pop();
obj.pop();
obj.display();
System.out.printf("\nTop element is %d\n",
obj.peek());
}
}
class StackUsingLinkedlist {
// A linked list node
private class Node {
int data; // integer data
Node link; // reference variable Node type
}
Node top;
// Constructor
StackUsingLinkedlist() { this.top = null; }
public void push(int x) // insert at the beginning
{
Node temp = new Node();
if (temp == null) {
System.out.print("\nHeap Overflow");
return;
}
temp.data = x;
temp.link = top;
top = temp;
}
public boolean isEmpty() { return top == null; }
// Utility function to return top element in a stack
public int peek()
{
if (!isEmpty()) {
return top.data;
}
else {
System.out.println("Stack is empty");
return -1;
}
}
public void pop() // remove at the beginning
{
if (top == null) {
System.out.print("\nStack Underflow");
return;
}
top = (top).link;
}
public void display()
{
if (top == null) {
System.out.printf("\nStack Underflow");
exit(1);
}
else {
Node temp = top;
while (temp != null) {
System.out.print(temp.data);
temp = temp.link;
if(temp != null)
System.out.print(" -> ");
}
}
}
}