forked from rampatra/Algorithms-and-Data-Structures-in-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedStack.java
107 lines (95 loc) · 2.04 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.rampatra.base;
import java.util.EmptyStackException;
/**
* Stack implementation using a singly linked list.
*
* @param <E> the data type to be stored in the stack
* @author rampatra
* @since 3/24/15
*/
public class LinkedStack<E> implements Stack<E> {
private Node<E> top;
public LinkedStack() {
top = null;
}
/**
* Pushes an item onto the top of this stack.
*
* @param item
*/
@Override
public E push(E item) {
top = new Node<>(item, top);
return item;
}
/**
* Removes the object at the top of this stack and
* returns it.
*
* @return
*/
@Override
public E pop() {
E item = peek();
top = top.next;
return item;
}
/**
* Looks at the object at the top of this stack without removing it from the stack.
*
* @return
*/
@Override
public E peek() {
if (top == null) {
throw new EmptyStackException();
}
return top.item;
}
/**
* Returns the number of items currently in the stack.
*
* @return
*/
@Override
public int size() {
int count = 0;
for (Node node = top; node != null; node = node.next) {
count++;
}
return count;
}
/**
* Prints the content of the stack.
*/
@Override
public void print() {
Node<E> node;
System.out.print("[");
if (top == null) {
System.out.println("]");
return;
}
for (node = top; node.next != null; node = node.next) {
System.out.print(node.item + ",");
}
System.out.println(node.item + "]");
}
/**
* Tests if this stack is empty.
*
* @return
*/
@Override
public boolean isEmpty() {
return top == null;
}
private class Node<E> {
E item;
Node<E> next;
Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
}