-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLLImplementation.java
More file actions
74 lines (60 loc) · 1.56 KB
/
LLImplementation.java
File metadata and controls
74 lines (60 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
package Stacks;
import java.util.EmptyStackException;
/**
* DiaAdv : Two data members, more space / time complexity is higher for display.
* Adv : Unlimited size.
*/
public class LLImplementation {
public static void main(String[] args) {
LLStack<String> stack = new LLStack<>();
stack.push("John");
stack.push("Roman");
stack.push("Brock");
System.out.println(stack.peek());
System.out.println(stack.pop());
System.out.println(stack.peek());
}
public static class Node<T> {
T data;
Node<T> next;
Node(T data) {
this.data = data;
}
}
public static class LLStack<T> {
Node<T> head = null;
int size = 0;
void push(T x) {
Node<T> temp = new Node<>(x);
temp.next = head;
head = temp;
size++;
}
T pop() {
if (head == null) {
throw new EmptyStackException();
}
T x = head.data;
head = head.next;
return x;
}
T peek() {
if (head == null) {
throw new EmptyStackException();
}
return head.data;
}
private void displayRec(Node<T> h) {
if (h == null) return;
displayRec(h.next);
System.out.print(h.data + " ");
}
void display() {
displayRec(head);
System.out.println();
}
int size() {
return size;
}
}
}