-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathA5Stack.java
More file actions
70 lines (62 loc) · 1.61 KB
/
A5Stack.java
File metadata and controls
70 lines (62 loc) · 1.61 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
//
//Dewei Yu
//V00897211
public class A5Stack<T> implements Stack<T> {
private Node<T> head;
public A5Stack() {
head = null;
}
/*
* Purpose: Insert an item onto the top of the stack
* Parameters: T - the item to insert
* Returns: Nothing
*/
public void push(T v) {
Node<T> node = new Node<T>(v);
node.next = head;
head = node;
}
/*
* Purpose: Removes and returns the top item from the stack
* Parameters: None
* Returns: T - the data value of the element removed
* Throws: EmptyStackException if stack is empty
*/
public T pop() {
if (isEmpty()) {
throw new EmptyStackException();
}
Node<T>node=head;
head=head.next;
return node.getData();
}
/*
* Purpose: Accesses the top item on the stack
* Parameters: None
* Returns: T - the data value of the top element
* Throws: EmptyStackException if stack is empty
*/
public T top() {
if (isEmpty()) {
throw new EmptyStackException();
}
Node<T>node = head;
return node.getData();
}
/*
* Purpose: Determines whether the stack is empty
* Parameters: None
* Returns: boolean - true if the stack is empty, false otherwise
*/
public boolean isEmpty() {
return head==null;
}
/*
* Purpose: Removes all elements from the stack
* Parameters: None
* Returns: Nothing
*/
public void popAll(){
head = null;
}
}