-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.java
81 lines (67 loc) · 1.73 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
//stack using singly linked list
import java.util.EmptyStackException;
public class Stack
{
//instance variables
private ListNode top;
private int length;
//node structure of the list
private class ListNode
{
private int data;
private ListNode next;
public ListNode(int data){
this.data = data;
}
}
//constructor of the Stack class
public Stack(){
top = null;
length = 0;
}
//returns length of the stack
public int length(){
return length;
}
//method to check if stack is empty
//true is stack is empty
public boolean isEmpty(){
return length == 0;
}
//inserts an element to the list
//it is an insert node at first position operation
public void push(int value){
ListNode temp = new ListNode(value);
temp.next = top;
top = temp;
length++;
}
//deletes an element
//deletes the most recent inserted element
//basically a delete first node operation
public int pop(){
if(isEmpty()){
throw new EmptyStackException();
}
int result = top.data;
top = top.next;
length++;
return result;
}
//returns the top most element of the stack
public int peek(){
if(isEmpty()){
throw new EmptyStackException();
}
return top.data;
}
public static void main(String[] args) {
Stack s = new Stack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.peek() + " is the peek element");
System.out.println(s.pop() + " is popped");
System.out.println(s.peek() + " is the peek element");
}
}