forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
100 lines (88 loc) · 1.95 KB
/
LinkedStack.java
File metadata and controls
100 lines (88 loc) · 1.95 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
package com.examplehub.datastructures.stack;
import com.examplehub.datastructures.linkedlist.Node;
import java.util.EmptyStackException;
import java.util.StringJoiner;
public class LinkedStack<E> {
/** The top of the stack. */
private Node<E> top;
/** The size of the stack. */
private int size;
/** Constructor. */
public LinkedStack() {
top = null;
size = 0;
}
/**
* Added to element to the top of the stack.
*
* @param element the element to be added.
* @return {@code true} if added successfully.
*/
public boolean push(E element) {
Node<E> newNode = new Node<>(element);
if (top != null) {
newNode.next = top;
}
top = newNode;
size++;
return true;
}
/**
* Remove element from the top of the stack.
*
* @return top element of the stack.
* @throws EmptyStackException if the stack is empty.
*/
public E pop() {
if (empty()) {
throw new EmptyStackException();
}
E retValue = top.data;
top = top.next;
size--;
return retValue;
}
/**
* Peek the top element of the stack.
*
* @return the top element of the stack.
* @throws EmptyStackException if the stack is empty.
*/
public E peek() {
if (empty()) {
throw new EmptyStackException();
}
return top.data;
}
/**
* Test if the stack is empty.
*
* @return {@code true} if the stack is empty, otherwise {@code false}.
*/
public boolean empty() {
return top == null;
}
/** Remove all elements of the stack. */
public void clear() {
top = null;
size = 0;
}
/**
* Return size of the stack.
*
* @return size of the stack.
*/
public int size() {
return size;
}
@Override
public String toString() {
StringJoiner joiner = new StringJoiner(", ", "[", "]");
Node<E> temp = top;
while (temp != null) {
joiner.add(temp.data.toString());
temp = temp.next;
}
return joiner.toString();
}
}