-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.java
More file actions
62 lines (54 loc) · 1.33 KB
/
LinkedStack.java
File metadata and controls
62 lines (54 loc) · 1.33 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
/**
* Your implementation of a linked stack.
*
* @author Quang Hai Dang Dam
* @version 1.0
*/
public class LinkedStack<T> implements StackInterface<T> {
// Do not add new instance variables.
private LinkedNode<T> head;
private int size;
public LinkedStack() {
head = null;
size = 0;
}
@Override
public boolean isEmpty() {
return head == null;
}
@Override
public T pop() {
if (isEmpty()) {
throw new java.util.NoSuchElementException("No more element exist\n");
}
T object = head.getData();
head = head.getNext();
size--;
return object;
}
@Override
public void push(T data) {
if (data == null) {
throw new java.lang.IllegalArgumentException("Cannot insert null data into data structure");
}
LinkedNode<T> linkedNode = new LinkedNode<T>(data, head);
head = linkedNode;
size++;
}
@Override
public int size() {
return size;
}
/**
* Returns the head of this stack.
* Normally, you would not do this, but we need it for grading your work.
*
* DO NOT USE THIS METHOD IN YOUR CODE.
*
* @return the head node
*/
public LinkedNode<T> getHead() {
// DO NOT MODIFY!
return head;
}
}