说明:本代码主要是实现了堆栈的进栈和出栈,还有堆栈的逆序操作。
#include "stdio.h"
2 #include "malloc.h"
3 #define STACK_NUM 20
4 struct Stack_Node;
5 typedef struct Stack_Node
6 {
7 int data;
8 struct Stack_Node *next;
9 }StackNode;
10
11
12 //define the fist stack node
13 static StackNode *stack_head = NULL;
14 void pop(void)
15 {
16 StackNode *old_head = NULL;
17 old_head = stack_head;
18 stack_head = stack_head->next;
19 free(old_head);
20 }
21
22 void push(int data)
23 {
24 StackNode *new_node = NULL;
25 new_node = (StackNode *)malloc(sizeof(StackNode));
26 if(new_node == NULL)
27 printf("malloc for new node fail.\n");
28
29 new_node->data = data;
30 new_node->next = stack_head;
31 stack_head = new_node;
32 }
33
34 void print_stack()
35 {
36 StackNode *node = NULL;
37 node = stack_head;
38 while(node != NULL){
39 printf("%d ",node->data);
40 node = node->next;
41 }
42 printf("\n");
43 }
44
45 void reverse_stack(void)
46 {
47 StackNode *pCurr = NULL;
48 StackNode *pNext = NULL;
49 pCurr = stack_head->next;
50 stack_head->next = NULL;
51 while(pCurr != NULL){
52 pNext = pCurr->next;
53 pCurr->next = stack_head;
54 stack_head = pCurr;
55 pCurr = pNext;
56 }
57 }
58 void main(void)
59 {
60 printf("to create the stack.\n");
61 int i;
62 for( i = 1;i <=STACK_NUM;i++){
63 push(i);
64 }
65 printf("--------print the original stack-------\n");
66 print_stack();
67 pop();
68 pop();
69 printf("--------print the stack after pop twice-------\n");
70 print_stack();
71 printf("--------print the stack after reverse it -------\n");
72 reverse_stack();
73 print_stack();
74 return;
75 }
执行结果:
kldong@ubuntu:~/learning/linux/stack/own$ ./run
to create the stack.
--------print the original stack-------
20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
--------print the stack after pop twice-------
18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
--------print the stack after reverse it -------
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18