forked from NITSkmOS/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
88 lines (78 loc) · 2.19 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
78
79
80
81
82
83
84
85
86
87
88
import java.util.NoSuchElementException;
public class Stack<Item>{
private int size; // size of the Stack
private Node first; // top of Stack
private class Node {
private Item item;
private Node next;
}
/**
* Creates an empty Stack instance
*/
public Stack() {
first = null;
size = 0;
}
/**
* Returns whether the Stack is empty or not.
*
* @return true if the Stack is empty, otherwise false.
*/
public boolean isEmpty() {
return first == null;
}
/**
* Returns the amount of times in this Stack.
*
* @return the amount of times in this Stack.
*/
public int getSize() {
return size;
}
/**
* Add an item to this Stack.
*
* @param item the item to add.
*/
public void push(Item item) {
Node oldFirst = first;
first = new Node();
first.item = item;
first.next = oldFirst;
size++;
}
/**
* Returns and removes the item on the top of this Stack.
*
* @throws NoSuchElementException if this Stack is empty
*/
public Item pop() throws NoSuchElementException{
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
Item item = first.item;
first = first.next;
size--;
return item;
}
/**
* Returns the top item of the Stack, without removing it.
*
* @return the item on top of this Stack
* @throws NoSuchElementException if this Stack is empty
*/
public Item peek() throws NoSuchElementException{
if (isEmpty()) throw new NoSuchElementException("Stack underflow");
return first.item;
}
/**
* Example usage
*/
public static void main(String[] args) throws NoSuchElementException {
Stack<String> Stack = new Stack<String>();
Stack.push("Hello World");
System.out.println(Stack.peek()); // "Hello World"
Stack.push("I am on the top now");
System.out.println(Stack.peek()); // "I am on the top now"
System.out.println(Stack.pop()); // "I am on the top now"
System.out.println(Stack.peek()); // "Hello World
}
}