-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspecial_stack.cpp
More file actions
83 lines (70 loc) · 1.4 KB
/
Copy pathspecial_stack.cpp
File metadata and controls
83 lines (70 loc) · 1.4 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
//
// special_stack.cpp
// algorithms
//
// Created by alifar on 7/29/16.
// Copyright © 2016 alifar. All rights reserved.
//
#include "special_stack.hpp"
// push: 4, 5, 6 -> [6, 5, 4]
SimpleStack::SimpleStack(){
head = 0;
next = 0;
}
void SimpleStack::push(int data){
if(!head){
head = new SimpleStack();
head->data = data;
head->next = 0;
return;
}
SimpleStack *node = new SimpleStack();
node->data = data;
node->next = head;
head = node;
}
void SimpleStack::pop(){
if(!head){
return;
}
SimpleStack *tmp = head;
delete head;
head = tmp->next;
}
SimpleStack * SimpleStack::top(){
return head ? head : 0;
}
bool SimpleStack::empty(){
return !head;
}
int SimpleStack::get_data(){
return data;
}
StackWithMin::StackWithMin(){
stack = new SimpleStack();
min_collection = new SimpleStack();
}
void StackWithMin::push(int data){
// 4, 5, 3: push->[3, 5, 4]; get_min = 4
if(stack->empty() || data < min_collection->top()->get_data()){
min_collection->push(data);
} else{
min_collection->push(min_collection->top()->get_data());
}
stack->push(data);
}
void StackWithMin::pop(){
if(stack->empty()){
return;
}
if(stack->top()->get_data() == min_collection->top()->get_data()){
min_collection->pop();
}
stack->pop();
}
SimpleStack * StackWithMin::top(){
return stack->top();
}
SimpleStack * StackWithMin::get_min(){
return min_collection->empty() ? 0 : min_collection->top();
}