-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminStack.java
More file actions
94 lines (76 loc) · 1.95 KB
/
minStack.java
File metadata and controls
94 lines (76 loc) · 1.95 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
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
import java.util.Scanner;
public class minStack
{
class Node{
Node next;
int data;
Node(int data){
this.data=data;
this.next=null;
}
}
Node top=null;
Node mintop=null;
void push(int data){
Node newnode=new Node(data);
newnode.next=top;
top=newnode;
if(mintop==null||data<=mintop.data){
Node minNode=new Node(data);
minNode.next=mintop;
mintop=minNode;
}
}
void pop(){
if(top==null){
System.out.print("empty stack");
return;
}
int removed=top.data;
top=top.next;
if(removed==mintop.data){
mintop=mintop.next;
}
}
void traverse(){
if(top==null){
System.out.println("empty");
return;
}
Node temp=top;
while(temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
int Stackmin(){
if(mintop==null){
System.out.println("no more min elements");
return -1;
}
return mintop.data;
}
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
minStack st=new minStack();
st.push(10);
st.push(20);
st.push(15);
st.push(5);
System.out.println("stack initially :");
st.traverse();
System.out.println("current min:"+st.Stackmin());
st.pop();
st.traverse();
System.out.println("current min:"+st.Stackmin());
st.pop();
st.traverse();
System.out.println("current min:"+st.Stackmin());
st.pop();
st.traverse();
System.out.println("current min:"+st.Stackmin());
st.pop();
st.traverse();
System.out.println("current min:"+st.Stackmin());
}
}