-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedStack.java
executable file
·91 lines (72 loc) · 1.82 KB
/
LinkedStack.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
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
package com.example.stack;
import com.example.exceptions.EmptyCollectionException;
import com.example.interfaces.StackADT;
public class LinkedStack<T> implements StackADT<T> {
private int count;
private LinearNode<T> top;
public LinkedStack() {
this.count = 0;
this.top = null;
}
/**
* {@inheritDoc }
*/
@Override
public void push(T element) {
LinearNode<T> newNode = new LinearNode<>(element);
if (this.top == null) {
this.top = newNode;
} else {
newNode.setNext(this.top);
this.top = newNode;
}
this.count++;
}
/**
* {@inheritDoc }
*/
@Override
public T pop() throws EmptyCollectionException {
LinearNode<T> toRemove;
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
toRemove = this.top;
this.top = toRemove.getNext();
this.count--;
return toRemove.getElement();
}
/**
* {@inheritDoc }
*/
@Override
public T peek() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
return this.top.getElement();
}
/**
* {@inheritDoc }
*/
@Override
public boolean isEmpty() {
return this.count == 0;
}
/**
* {@inheritDoc }
*/
@Override
public int size() {
return this.count;
}
protected String print() {
StringBuilder s = new StringBuilder();
LinearNode<T> current = this.top;
while (current != null) {
s.append(current.getElement()).append(" ");
current = current.getNext();
}
return s.toString();
}
}