0%

#02 栈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/***
**************************************************************
* *
* .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-. *
* | ______ | *
* | .-" "-. | *
* | / \ | *
* | _ | | _ | *
* | ( \ |, .-. .-. ,| / ) | *
* | > "=._ | )(__/ \__)( | _.=" < | *
* | (_/"=._"=._ |/ /\ \| _.="_.="\_) | *
* | "=._"(_ ^^ _)"_.=" | *
* | "=\__|IIIIII|__/=" | *
* | _.="| \IIIIII/ |"=._ | *
* | _ _.="_.="\ /"=._"=._ _ | *
* | ( \_.="_.=" `--------` "=._"=._/ ) | *
* | > _.=" "=._ < | *
* | (_/ \_) | *
* | | *
* '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' *
* *
* 栈 *
**************************************************************
*/

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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
int data;
struct Node *next;
} Node;

Node *initStack() {
Node *S = (Node *)malloc(sizeof(Node));
S->data = 0;
S->next = NULL;

return S;
}

bool isEmpty(Node *S) {
if (S->data == 0)
return true;

return false;
}

int pop(Node *S) {
if (isEmpty(S))
return -1;

Node *node = S->next;
S->next = node->next;

int data = node->data;
free(node);
S->data--;

return data;
}

bool push(Node *S, int data) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = data;

node->next = S->next;
S->next = node;
S->data++;

return true;
}

void printStack(Node *S) {
Node *node = S->next;

printf("S(%d) ", S->data);
while (node) {
printf("-> %d ", node->data);
node = node->next;
}
printf("\n");
}

int main(int argc, char **argv) {
Node *S = initStack();

push(S, 1);
printStack(S);
push(S, 2);
printStack(S);
push(S, 3);
printStack(S);

printf("\n");
printf("%d\n", pop(S));
printStack(S);
printf("%d\n", pop(S));
printStack(S);
printf("%d\n", pop(S));
printStack(S);
printf("%d\n", pop(S));
printStack(S);
printf("%d\n", pop(S));
printStack(S);

return 0;
}