-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathStackLinkedList.java
55 lines (44 loc) · 1.09 KB
/
StackLinkedList.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
package ds.stack;
import java.util.NoSuchElementException;
public class StackLinkedList<E> {
private int size;
private Node head;
public void push(E elem) {
if (elem == null) throw new NullPointerException();
Node sentinel = new Node(elem);
sentinel.next = head;
head = sentinel;
size++;
}
public E peek() {
if (head == null) throw new NoSuchElementException();
return head.elem;
}
public E pop() {
if (head == null) throw new NoSuchElementException();
head = head.next;
size --;
return head.elem;
}
public void iterate() {
Node temp = head;
while (temp != null) {
System.out.println(temp.elem);
temp = temp.next;
}
}
public int getSize() {
return size;
}
class Node {
private E elem;
private Node next;
public Node(E elem) {
this.elem = elem;
}
public Node(E elem, Node next) {
this.elem = elem;
this.next = next;
}
}
}