-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackClass
113 lines (95 loc) · 2.62 KB
/
StackClass
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
/**
* Copied from Prof. Conrad's GitHub.
*/
package stack;
public class Stack<T extends Object> {
private Node<T> top;
public Stack()
{
top = null;
} // end constructor which creates empty stack w/null top node
public void push(T newItem)
{
Node<T> new_node = new Node(newItem, top); // the node is created and pointer to the previously top node is created
top = new_node; // designation "top" is moved to the new node.
}
public T peek()
{
if ( isEmpty() )
return null;
return top.getData();
} // This is the reverse of the pseudocode, but works equally well
public T pop()
{
T value = this.peek();
if ( value != null )
{
Node<T> oldTop = top;
top = top.getNext();
oldTop = null;
}
return value;
}
public boolean isEmpty()
{
return top==null;
}
public void clear() //many implementations don't use this, since @end, everything has been popped
{
top = null;
}
public void display()
{
Node<T> current = top;
if ( current == null )
System.out.println("Stack is empty");
else
{
while ( current != null )
{
System.out.print(current.getData()+" ");
current = current.getNext();
}
System.out.println();
}
}
@Override
public String toString()
{
Node<T> current = top;
String temp = "T:";
if ( current == null )
temp = "(Empty)";
else
{
while ( current != null )
{
temp = temp + " (" + current.getData() + ")";
current = current.getNext();
}
}
return temp;
}
// this is a private inner class, only needs to be used by the
// public outer linkedlist class
private class Node<T> {
// next node in the linked list, if null, then end of list
Node next;
// data element of the node
T data;
// constructor for if we want to specify a particular node for
// the node to point to
public Node(T dataValue, Node nextNode) {
next = nextNode;
data = dataValue;
}
// return the data in the node
public T getData() {
return data;
}
// returns the next node, if any
public Node getNext() {
return next;
}
}
}