数据结构——栈(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 }

 

 

 

你可能感兴趣的:(数据结构)