-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_min.cpp
106 lines (63 loc) · 1.13 KB
/
stack_min.cpp
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
102
103
104
105
106
#include<iostream>
using namespace std;
struct node{
struct node* next;
int val;
struct node* next_min;
};
struct node* minN;
void push(struct node** p, int n)
{
struct node* t = (struct node*)malloc(sizeof(struct node));
t-> next = NULL;
t -> val =n;
if((*p) == NULL)
{
(*p) = t;
t -> next_min = NULL;
minN = t;
}
else
{
t -> next = (*p);
(*p) = t;
if(minN ->val > n)
{
t -> next_min = minN;
minN = t;
}
}
}
void pop(struct node** p)
{
if((*p) == NULL) return;
if((*p) -> val == minN -> val)
{
minN = (*p) -> next_min;
}
struct node* t = (*p);
(*p) = (*p) -> next;
free(t);
}
int top(struct node* p)
{
if(p == NULL) {cout << "empty stack"<< endl; return -1;}
return p -> val;
}
int getMin(struct node* p)
{
if(p == NULL) {cout << "empty stack"<< endl; return -1;}
return minN -> val;
}
int main()
{
struct node* head = NULL;
push(&head, 9);
push(&head, 8);
push(&head, 6);
push(&head, 1);
pop(&head);
cout << top(head) << endl;
cout << getMin(head) << endl;
return 0;
}