-
Notifications
You must be signed in to change notification settings - Fork 65
/
LinkedListBasedStack.java
103 lines (88 loc) · 1.57 KB
/
LinkedListBasedStack.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
89
90
91
92
93
94
95
96
97
98
99
100
101
/**
* Data-Structures-In-Java
* LinkedListBasedStack.java
*/
package com.deepak.data.structures.Stack;
import java.util.NoSuchElementException;
/**
* Linked List based implementation of stack
*
* @author Deepak
*/
public class LinkedListBasedStack {
/**
* Top node of the Stack
*/
private Node top = null;
/**
* Method to push a item on the stack
*
* @param item
*/
public void push(Object item) {
top = new Node(item, top);
}
/**
* Method to remove a item from the stack
*
* @return {@link Object}
*/
public Object pop() {
if (top == null) {
throw new IllegalStateException("Cannot pop from a empty stack");
}
Object result = peek();
top = top.next;
return result;
}
/**
* Method to find out top element on Stack
*
* @return {@link Object}
*/
public Object peek() {
if (top == null) {
throw new NoSuchElementException("Cannot peek from a empty stack");
}
return top.item;
}
/**
* Method to find size of the Stack
*
* @return {@link int}
*/
public int size() {
int size = 0;
for (Node node = top; node != null; node = node.next) {
size++;
}
return size;
}
/**
* Method to check if Stack is Empty
*
* @return {@link boolean}
*/
public boolean isEmpty() {
return top == null;
}
/**
* Node class for Stack
*
* @author Deepak
*/
private class Node {
private Object item;
private Node next;
/**
* Constructor for creating a new Node
*
* @param item
* @param next
*/
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
}
}