-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLimplementation.java
More file actions
88 lines (77 loc) · 1.95 KB
/
LLimplementation.java
File metadata and controls
88 lines (77 loc) · 1.95 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
public class LLimplementation {
public static class Node {
int val;
Node next;
Node(int val) {
this.val = val;
this.next = null;
}
}
public static class LLStack {
private Node head = null;
private 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;
size--;
return x;
}
int peek() {
if (head == null) {
System.out.println("Stack is empty");
return -1;
}
return head.val;
}
boolean isEmpty() {
return head == null;
}
boolean isFull() {
return false; // Linked list stack is never full unless memory is exhausted
}
void display() {
Node temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
System.out.println();
}
void displayRev() {
Node temp = head;
while (temp != null) {
System.out.print(temp.val + " ");
temp = temp.next;
}
System.out.println();
}
int size() {
return size;
}
}
public static void main(String[] args) {
LLStack st = new LLStack();
st.push(1);
st.display();
st.push(2);
st.display();
st.push(3);
st.display();
System.out.println(st.size);
st.pop();
st.display();
System.out.println(st.size());
st.push(0);
st.push(7);
}
}