-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinkedStack.java
More file actions
88 lines (67 loc) · 1.5 KB
/
Copy pathlinkedStack.java
File metadata and controls
88 lines (67 loc) · 1.5 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 LinkedStack<T> implements Stack<T> {
private Node<T> top;
public LinkedStack() {
top = null;
}
@Override
public void push(T item) {
top = new Node<T>(item, top);
}
@Override
public T pop() throws StackUnderflowException{
if(top != null) {
Node<T> oldTop = top;
top = top.getNext();
return oldTop.getValue();
} else {
throw new StackUnderflowException("trying to pop from an empty stack\n");
}
}
@Override
public T peek() throws StackUnderflowException {
if(top != null) {
return top.getValue();
} else {
throw new StackUnderflowException("trying to peek from an empty stackn");
}
}
public boolean isEmpty() {
return top == null;
}
//method to modified the output information
public String toString(){
String stackString =" ";
Node<T> node;
node =top;
while (node != null) {
//stack should the order starting from the top
stackString =node.getValue() +" "+stackString+" ";
node =node.getNext();
}
return stackString;
}
@SuppressWarnings("hiding")
private class Node<T> {
private T value;
private Node<T> next;
public T getValue() {
return value;
}
@SuppressWarnings("unused")
public void setValue(T value) {
this.value = value;
}
public Node<T> getNext() {
return next;
}
@SuppressWarnings("unused")
public void setNext(Node<T> next) {
this.next = next;
}
public Node(T value, Node<T> next) {
super();
this.value = value;
this.next = next;
}
}
}