天天看點

41深入了解C指針之---指針與棧

深入了解C指針之---指針與棧

  一、借助第40指針與連結清單的相關内容,稍微修改即可:

   1、定義頭檔案stack.h代碼如下:

1 #include <stdlib.h>
 2 #include <stdio.h>
 3
 4 #ifndef stack_h
 5 #define stack_h
 6 typedef int DataType;
 7
 8 typedef struct _node{
 9     DataType data;
10     struct _node *next;
11 } Node;
12
13 typedef struct _stack{
14     Node *head;
15     Node *tail;
16 } Stack;
17
18 void initStack(Stack *);
19 void pushStack(Stack *, DataType);
20 void popStack(Stack *);
21 int getLength(Stack *);
22 void dispStack(Stack *);
23
24 #endif      

  頭檔案中依舊是完成資料類型的聲明和資料的操作函數的聲明。

   2、頭檔案對應的實作檔案stack.c代碼如下:

1 #include "stack.h"
 2
 3 //棧初始化
 4 void initStack(Stack *stack){
 5     stack->head = NULL;
 6     stack->tail = NULL;
 7 }
 8
 9 //棧入
10 void pushStack(Stack *stack, DataType iData){
11     Node *node = (Node *)malloc(sizeof(Node));
12     node->data = iData;
13     node->next = NULL;
14
15     if(stack->head == NULL){
16         stack->tail = node;
17     }else{
18         node->next = stack->head;
19     }
20     stack->head = node;
21
22     return;
23
24 }
25
26 //棧出
27 void popStack(Stack *stack){
28     if(stack->head->next == NULL){
29         stack->head = NULL;;
30     }else{
31         stack->head = stack->head->next;
32     }
33
34     return;
35 }
36
37 //棧長度
38 int getLength(Stack *stack){
39     Node *node = stack->head;
40     int i = 0;
41     while(node != NULL){
42         node = node->next;
43         i++;
44     }
45
46     return i;
47 }
48
49 //棧輸出
50 void dispStack(Stack *stack){
51     Node *node = stack->head;
52     int i = 0;
53     while(node != NULL){
54         printf("the %dth node: %d\n", i + 1, node->data);
55         node = node->next;
56         i++;
57     }
58     printf("disp finished!\n");
59
60     return;
61 }      

  代碼說明:

    1、入棧函數使用連結清單的頭插法

1 #include "stack.h"
 2
 3 int main(int argc, char **argv)
 4 {
 5     Stack *stack1 = (Stack *)malloc(sizeof(Stack));
 6     printf("the first:\n");
 7     initStack(stack1);
 8     pushStack(stack1, 1);
 9     pushStack(stack1, 3);
10     pushStack(stack1, 5);
11     pushStack(stack1, 7);
12     pushStack(stack1, 9);
13     printf("The length: %d\n", getLength(stack1));
14     dispStack(stack1);
15     printf("the second:\n");
16     popStack(stack1);
17     printf("The length: %d\n", getLength(stack1));
18     dispStack(stack1);
19     popStack(stack1);
20     dispStack(stack1);
21     printf("The length: %d\n", getLength(stack1));
22     pushStack(stack1, 11);
23     dispStack(stack1);
24     printf("The length: %d\n", getLength(stack1));
25
26     return 0;
27 }      

人就像是被蒙着眼推磨的驢子,生活就像一條鞭子;當鞭子抽到你背上時,你就隻能一直往前走,雖然連你也不知道要走到什麼時候為止,便一直這麼堅持着。