-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListStack.java
60 lines (53 loc) · 1.11 KB
/
LinkedListStack.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
import java.util.NoSuchElementException;
/**
* An implementation of a stack as a sequence of nodes.
* */
public class LinkedListStack
{
private Node first;
/**
* Constructs an empty stack.
*/
public LinkedListStack()
{
first = null;
}
/**
* Adds an element to the top of the stack.
* @param element the element to add
*/
public void push(Object element)
{
Node newNode = new Node();
newNode.data = element;
newNode.next = first;
first = newNode;
}
/**
* Removes the lement from the top of the stack.
* @return the removed element
*/
public Object pop()
{
if (first == null)
{
throw new NoSuchElementException();
}
Object element = first.data;
first = first.next;
return element;
}
/**
* Checks whether this stack is empty
* @return true if stack is empty
*/
public boolean empty()
{
return first == null;
}
public class Node
{
public Object data;
public Node next;
}
}