-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
85 lines (66 loc) · 1.59 KB
/
stack.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
// Node* createNode(int val){
// Node* stackNode = (Node *)malloc(sizeof(Node));
// stackNode->val = val;
// stackNode->next = nullptr;
// return stackNode;
// }
#include <iostream>
using namespace std;
struct Node{
int val;
Node *next = NULL;
};
struct Stack{
int size = 0;
Node *top = NULL;
};
Node* createNode(int value){
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->val = value;
newNode->next = nullptr;
return newNode;
}
Stack* createStack(){
Stack *newStack = (Stack*) malloc(sizeof(Stack));
newStack->top = nullptr;
newStack->size = 0;
return newStack;
}
void push(Node *newNode, Stack *myStack){
newNode->next = myStack->top;
myStack->top = newNode;
myStack->size++;
}
void pop(Stack *myStack){
Node *temp = myStack->top;
myStack->top = temp->next;
temp->next = nullptr;
myStack->size--;
free(temp);
}
void printStack(Stack *myStack){
Node *temp = myStack->top;
while(temp != NULL){
cout << temp->val << endl;
temp = temp->next;
}
cout << "--------" << endl;
}
int main(){
Node *head = (Node*) malloc(sizeof(Node));
Stack *myStack = createStack();
cout <<"Size: " << myStack->size << endl;
push(createNode(3), myStack);
push(createNode(5), myStack);
push(createNode(7), myStack);
push(createNode(9), myStack);
printStack(myStack);
pop(myStack);
pop(myStack);
// push(createNode(13), myStack);
pop(myStack);
pop(myStack);
printStack(myStack);
cout <<"Size: " << myStack->size << endl;
return 0;
}