-
Notifications
You must be signed in to change notification settings - Fork 0
/
lec69_implementation_LL_stack.java
74 lines (67 loc) · 1.75 KB
/
lec69_implementation_LL_stack.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
package shreya.java;
import java.util.Stack;
public class lec69_implementation_LL_stack {
public static class Node{ //user defined data type
int val;
Node next;
Node(int val){
this.val =val;
}
}
public static class LLStack{ //user defined data structure
Node head = null;
int size =0;
void push(int x){
Node temp = new Node(x);
temp.next = head;
head = temp;
size++;
}
int pop(){
if(head==null){
System.out.println("stack is empty");
return -1;
}
int x = head.val;
head = head.next;
return x;
}
int peek(){
if(head == null){
System.out.println("Stack is empty");
return -1;
}
return head.val;
}
void displayrec(Node h){
if(h==null)return;
displayrec(h.next);
System.out.print(h.val+" ");
}
void display(){
displayrec(head);
System.out.println();
}
int size(){ //getter
return size;
}
boolean isEmpty(){
if(size==0)return true;
return false;
}
}
public static void main(String[] args) {
LLStack st = new LLStack();
st.push(4);
st.push(3);
st.push(1);
st.push(5);
// st.push(9);
st.display();
System.out.println(st.pop());
st.display();
System.out.println(st.peek());
st.display();
System.out.println(st.size());
}
}