forked from matthewsamuel95/ACM-ICPC-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack_using_linked_list.cpp
92 lines (83 loc) · 1.98 KB
/
stack_using_linked_list.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
#include <bits/stdc++.h>
using namespace std;
#define stack_empty -1
class pilha{
private:
struct node{
int dado;
node *prox;
};
node *head = nullptr;
public:
void push(int val){
node* elemento;
elemento = new node;
elemento->dado = val;
if(head == nullptr){
//pilha vazia
elemento->prox = nullptr;
head = elemento;
}else{
//pilha com elemento
elemento->prox = head;
head = elemento;
}
}
bool isempty(){
if(head == nullptr){
return true;
}
return false;
}
int pop(){
int val = stack_empty;
if(!isempty()){
val = head->dado;
node *next, *at;
next = head->prox;
at = head;
head = next;
delete at;
}
return val;
}
int show_top(){
int val = stack_empty;
if(!isempty()){
val = head->dado;
}
return val;
}
int size(){
int cont = 0;
node* aux;
aux = head;
while(aux->prox !=nullptr){
cont++;
aux = aux->prox;
}
cont++;
return cont;
}
};
int main(){
pilha st;
int val;
for(int i = 0; i < 10; i++){
st.push((i+1));
}
for(int i = 0; i <12; i++){
val = st.pop();
if(val != stack_empty){
cout << val << endl;
}else{
cout << "stack is empty!" << endl;
}
}
for(int i = 0; i < 5; i++){
st.push((i+1));
}
cout << "stack have " << st.size() << " elements" << endl;
cout << st.show_top() << " is top element of stack" << endl;
return 0;
}