-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.java
51 lines (40 loc) · 922 Bytes
/
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
package com.keshav.ctci.queue;
import com.keshav.ctci.list.LLNode;
/*
Stack implemented using a linkedlist
push(): top of stack
pop() : delete top of statck and return
peek(): return top node
*/
public class Stack<T> {
private LLNode<T> head;
private int size=0;
public Stack() {}
// Push to top of stack
public void push(T val) {
LLNode<T> node = new LLNode<T>(val);
if (head != null) {
head = node;
}
node.next = head;
head = node;
size++;
}
// Return head
public T peek() {
return (head != null ? head.val() : null);
}
// Return head and delete
public T pop() {
T val = null;
if (head != null) {
val = head.val();
head = head.next;
size--;
}
return val;
}
public boolean isEmpty() {
return (size == 0);
}
}