forked from srdelisser/Assignment-5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
124 lines (91 loc) · 2.68 KB
/
LinkedStack.java
File metadata and controls
124 lines (91 loc) · 2.68 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/** Implements the interface <code>Stack</code> using linked elements.
*
*
* @author Marcel Turcotte (turcotte@eecs.uottawa.ca)
*/
public class LinkedStack<E> implements Stack<E> {
// Objects of the class Elem are used to store the elements of the
// stack.
private static class Elem<T> {
private T value;
private Elem<T> next;
private Elem(T value, Elem<T> next) {
this.value = value;
this.next = next;
}
}
// Reference to the top element
private Elem<E> top;
/** Returns <code>true</code> if this stack is empty, and
* <code>false</code> otherwise.
*
* @return <code>true</code> if this stack is empty, and
* <code>false</code> otherwise.
*/
public boolean isEmpty() {
return top == null;
}
/** Inserts an element onto the stack.
*
* @param value the element to be inserted
*/
public void push(E value) {
if (value == null) {
throw new NullPointerException();
}
top = new Elem<E>(value, top);
}
/** Returns the top element, without removing it.
*
* @return the top element
*/
public E peek() {
// pre-condition: the stack is not empty
return top.value;
}
/** Removes and returns the top element.
*
* @return the top element
*/
public E pop() {
// pre-condition: the stack is not empty
E saved = top.value;
top = top.next;
return saved;
}
/** Removes the top element of the stack. The element inserted at
* the bottom of the stack.
*/
//not sure best way to go about this
//start by poping the top, adding to new temp stack, iterating over remaining stack to add to temp
//then replace old stack with temp stack
public void roll() {
throw new UnsupportedOperationException("Invalid operation for linked stack. Method roll.");
}
/** Removes the botttom element. The element is inserted on the
* top of the stack.
*/
//ok so make new temp stack, iterate from second to end
//push first onto temp
//replace old with temp
public void unroll() {
throw new UnsupportedOperationException("Invalid operation for linked stack. Method unroll.");
}
/** Returns a string representation of the stack.
*
* @return a string representation
*/
@Override public String toString() {
StringBuffer stackStr = new StringBuffer("{");
Elem<E> current = top;
while (current != null) {
stackStr.append(current.value);
if (current.next != null) {
stackStr.append(",");
}
current = current.next;
}
stackStr.append("}");
return stackStr.toString();
}
}