-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.java
More file actions
44 lines (33 loc) · 714 Bytes
/
Stack.java
File metadata and controls
44 lines (33 loc) · 714 Bytes
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
package datastructure.stack;
public class Stack<E> {
private Node<E> head;
public Stack() {
head = null;
}
public void push(E data) {
head = new Node<E>(data, head);
}
public E pop() throws NoSuchElementException {
Node<E> temp;
if (head == null)
throw new NoSuchElementException("No element to pop");
else {
temp = head;
head = head.next;
}
return temp.data;
}
// Peek at the first element of the stack
public E peek() {
return head.data;
}
// print the content of the stack
public void printContent() {
Node<E> temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
} // end of Stack class