forked from CodeSadhu/Hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StackUsingLinkedList.java
70 lines (62 loc) · 1.58 KB
/
StackUsingLinkedList.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
public class StackUsingLinkedList {
static class Node{
int data;
Node next;
Node(int x){
data = x;
next = null;
}
}
Node head = null;
public void push(int x){
Node newNode = new Node(x);
if(head==null)
head = newNode;
else{
Node temp = head;
head = newNode;
head.next = temp;
}
System.out.println(x + " pushed into stack");
}
public int pop(){
if(head==null){
System.out.println("Stack is Empty");
return -1;
}
else
{
int popped = head.data;
head = head.next;
return popped;
}
}
public int peek()
{
if (head == null) {
System.out.println("Stack is empty");
return -1;
}
else {
return head.data;
}
}
public boolean isEmpty(){
if(head==null)
return true;
else
return false;
}
public static void main(String[] args) {
StackUsingLinkedList s = new StackUsingLinkedList();
s.push(20);
s.push(40);
s.push(30);
System.out.println(s.pop() + " popped out of stack");
System.out.println("Top Element = " + s.peek());
System.out.println("Is stack empty? " + s.isEmpty());
System.out.println(s.pop() + " popped out of stack");
System.out.println(s.pop() + " popped out of stack");
System.out.println("Is stack empty? " + s.isEmpty());
}
}