-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
55 lines (39 loc) · 1.15 KB
/
LinkedStack.java
File metadata and controls
55 lines (39 loc) · 1.15 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
import java.io.*;
public class LinkedStack<E> implements Stack<E>, Serializable {
private static class Elem<T> implements Serializable{
private T info;
private Elem<T> next;
private Elem( T info, Elem<T> next) {
this.info = info;
this.next = next;
}
}
private Elem<E> top; // instance variable
public LinkedStack() {
top = null;
}
public boolean isEmpty() {
return top == null;
}
public void push( E info ) {
if(info == null)
throw new NullPointerException("Cannot stack a null object");
top = new Elem<E>( info, top );
}
public E peek() {
if (isEmpty())
throw new EmptyStackException("Empty stack");
return top.info;
}
public E pop() {
if (isEmpty())
throw new EmptyStackException("Empty stack");
E savedInfo = top.info;
Elem<E> oldTop = top;
Elem<E> newTop = top.next;
top = newTop;
oldTop.info = null; // scrubbing the memory
oldTop.next = null; // scrubbing the memory
return savedInfo;
}
}