栈(C语言实现)

数据结构——栈(C语言实现)

 1
 /*
stack头文件
*/

2 #include < stdio.h >
3 #include < stdlib.h >
4
5 typedef struct Node
6 {
7 int data;
8 struct Node * next;
9 }StackNode;
10
11   void initStack(StackNode * top)
12 {
13 top -> next = NULL;
14 }
15
16   int IsEmpty(StackNode * top)
17 {
18 if (top -> next == NULL)
19 return 1 ;
20 return 0 ;
21 }
22
23   void Push(StackNode * top, int item)
24 {
25 StackNode * temp = (StackNode * )malloc( sizeof (StackNode));
26 if (temp == NULL)
27 {
28 printf( " malloc memory fail " );
29 exit( 1 );
30 }
31 temp -> data = item;
32 temp -> next = top -> next;
33 top -> next = temp;
34 }
35
36   int Pop(StackNode * top)
37 {
38 StackNode * temp;
39 int tempint;
40 if (top == NULL)
41 {
42 printf( " There is no elements/n " );
43 exit( 1 );
44 }
45 temp = top -> next;
46 tempint = temp -> data;
47 top -> next = temp -> next;
48 free(temp);
49 return tempint;
50 }
51
52   int GetTop(StackNode * top)
53 {
54 if (top == NULL)
55 {
56 printf( " There is no elements/n " );
57 exit( 1 );
58 }
59 return top -> next -> data;
60 }
61
62 void ClearStack(StackNode * top)
63 {
64 StackNode * temp;
65 while (top)
66 {
67 temp = top;
68 top = top -> next;
69 free(temp);
70 }
71 }


1 /* 测试stack */
2 #include " StackList.h "
3
4 int main()
5 {
6 int temp;
7 StackNode * top;
8 top = (StackNode * )malloc( sizeof (StackNode));
9 initStack(top);
10 Push(top, 10 );
11 Push(top, 20 );
12 temp = Pop(top);
13 printf( " %d/n " ,temp);
14 temp = GetTop(top);
15 printf( " %d/n " ,temp);
16
17 Pop(top);
18 // Pop(top);
19 temp = IsEmpty(top);
20 printf( " %d/n " ,temp);
21 ClearStack(top);
22
23 }

http://www.cnblogs.com/hstcghost/archive/2010/11/07/1871050.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值