-
Notifications
You must be signed in to change notification settings - Fork 1
/
Stack.java
77 lines (66 loc) · 1.88 KB
/
Stack.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
/**
* Program #2
* The following program uses the methods from LinearList class
* to implement a Stack
* CS310-1
* 03-11-2019
* @author Pranav Kalra cssc1483
*/
package data_structures;
import java.util.Iterator;
public class Stack<E extends Comparable<E>> implements Iterable<E>{
LinearList<E> linearList = new LinearList<E>();
/* inserts the object obj into the stack
*/
public void push(E obj) {
linearList.addFirst(obj);
}
/* pops and returns the element on the top of the stack
*/
public E pop() {
return linearList.removeFirst();
}
/* returns the number of elements currently in the stack
*/
public int size() {
return linearList.size();
}
/* return true if the stack is empty, otherwise false
*/
public boolean isEmpty() {
return linearList.isEmpty();
}
/* returns but does not remove the element on the top of the stack
*/
public E peek() {
return linearList.peekFirst();
}
/* returns true if the object obj is in the stack,
* otherwise false
*/
public boolean contains(E obj) {
return linearList.contains(obj);
}
/* returns the stack to an empty state
*/
public void makeEmpty() {
linearList.clear();
}
/* removes the Object obj if it is in the stack and
* returns true, otherwise returns false.
*/
public boolean remove(E obj) {
if (linearList.remove(obj) == null)
return false;
else {
linearList.remove(obj);
return true;
}
}
/* returns a iterator of the elements in the stack. The elements
* must be in the same sequence as pop() would return them.
*/
public Iterator<E> iterator() {
return linearList.iterator();
}
}