-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedStack.java
92 lines (70 loc) · 1.75 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
package projectCode20280;
/*
The LinkedStack<E> class implements the Stack<T> interface.
My LinkedStack class is made with a SinglyLinkedList as the underlying structure that holds
the information contained in the stack.
The addLast() and removeLast() methods of the SinglyLinkedList are used to implement the
push() and pop() methods of the stack interface.
*/
public class LinkedStack<E> implements Stack<E> {
private SinglyLinkedList<E> list = new SinglyLinkedList<>();
public LinkedStack()
{
;
}
@Override
public int size() {
return list.size();
}
@Override
public boolean isEmpty() {
return list.isEmpty();
}
/**
* Add element to the top of the stack (end of the list)
*
* @param e Element to be added
*/
@Override
public void push(E e) {
list.addLast(e);
}
@Override
public E top() {
return list.get(size()-1);
}
/**
* Removes and returns and element from the top of the stack
*
* @return E Element being removed
*/
@Override
public E pop() {
E e = list.removeLast();
return e;
}
public String toString()
{
return list.toString();
}
public static void main(String[] args) {
LinkedStack<Integer> stack = new LinkedStack<Integer>();
System.out.println("Push 3: ");
stack.push(3);
System.out.println(stack + "\n");
System.out.println("Push 6: ");
stack.push(6);
System.out.println(stack + "\n");
System.out.println("Push 14: ");
stack.push(14);
System.out.println(stack + "\n");
System.out.println("Pop: ");
stack.pop();
System.out.println(stack + "\n");
System.out.println("Size is " + (stack.size()) + "\n");
System.out.println("Top is " + stack.top() + "\n");
System.out.println("Push 60: ");
stack.push(60);
System.out.println(stack);
}
}