-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.cc
110 lines (100 loc) · 1.61 KB
/
Stack.cc
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
107
108
109
110
#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct StackNode
{
int data;
StackNode *next;
}Node;
class Stack{
public:
Stack():count(0),bottom(NULL),top(NULL){};
void pop();
void push(int);
void push(Node *);
Node * peek();
void print();
~Stack() { deleteStack(); };
void deleteStack();
private:
int count;
Node *bottom;
Node *top;
};
void Stack::deleteStack()
{
Node *cur = top;
Node *next = NULL;
while(cur != NULL)
{
next = cur->next;
free(cur);
cur = next;
}
top = bottom = NULL;
count = 0;
}
void Stack::push(int data)
{
Node *tmp = (Node *)malloc(sizeof(Node));
if (tmp == NULL)
{
cout << "malloc failed" << endl;
return;
}
tmp->data = data;
tmp->next = top;
top = tmp;
if (count == 0)
bottom = tmp;
++count;
}
void Stack::push(Node *node)
{
if (node == NULL)
{
cout << "input is null" << endl;
return;
}
node->next = top;
top = node;
if (bottom == NULL)
bottom = node;
++count;
}
void Stack::pop()
{
if (top == NULL)
return;
Node *tmp = top;
top = top->next;
free(tmp);
--count;
if (count == 0)
top = bottom = NULL;
}
Node * Stack::peek()
{
if (count > 0)
return top;
else
return NULL;
}
void Stack::print()
{
Node *tmp = top;
while(tmp != NULL)
{
cout << tmp->data << " ";
tmp=tmp->next;
}
}
int main()
{
Stack s;
for (int i=0; i<10; ++i)
{
s.push(i);
}
s.print();
}