数据结构---栈的链表实现

栈的链表实现C代码如下:

  1 #include <stdio.h>
  2 
  3 typedef int ElemType;
  4 
  5 
  6 typedef struct node
  7 {
  8     ElemType Data;
  9     struct node *next;
 10 }Node;
 11 
 12 typedef struct stack
 13 {
 14     Node *top;
 15 }Stack;
 16 
 17 //初始化栈
 18 void InitStack(Stack *S)
 19 {
 20     S->top=NULL;
 21 }
 22 
 23 //入栈
 24 int PushStackValue(Stack *S)
 25 {
 26     printf("Input the Value of stack member:\n(0-exit)\n");
 27     int value;
 28     int i=1;
 29     Node *NewNode=(Node *)malloc(sizeof(Node));
 30     printf("Please input the %dst value of stack:\n",i);
 31     scanf("%d",&value);
 32     NewNode->Data=value;
 33     NewNode->next=S->top;
 34     S->top=NewNode;
 35     i++;
 36     while(value)
 37     {
 38         Node *NewNode=(Node *)malloc(sizeof(Node));
 39         printf("Please input the %dst value of stack:\n",i);
 40         scanf("%d",&value);
 41         if(value!=0)
 42             i++;
 43         NewNode->Data=value;
 44         NewNode->next=S->top;
 45         S->top=NewNode;
 46     }
 47     S->top=S->top->next;
 48     return i-1;
 49 }
 50 
 51 //出栈
 52 int PopStackValue(Stack *S,int len)
 53 {
 54 
 55     if(len>0)
 56     {
 57         printf("the stack %dst value pop out: %d\n",len,S->top->Data);
 58     }
 59     else
 60     {
 61         printf("The Stack is empty\n");
 62     }
 63     len--;
 64     S->top=S->top->next;
 65     return len;
 66 }
 67 
 68 //判断栈空
 69 void IsEmpty(Stack *S)
 70 {
 71     if(S->top==NULL)
 72     {
 73         printf("The Stack is empty.\n");
 74     }
 75     else
 76     {
 77         printf("The stack is not empty.\n");
 78     }
 79 }
 80 
 81 
 82 //清空栈
 83 void ClearStack(Stack *S)
 84 {
 85     S->top=NULL;
 86 }
 87 
 88 //遍历栈
 89 Stack * ScanStack(Stack *S)
 90 {
 91     Stack *Temp=S;
 92     printf("The all stack member(from top to bottom) is:\n");
 93     while(S->top!=NULL)
 94     {
 95         printf("%d ",S->top->Data);
 96         S->top=S->top->next;
 97     }
 98     printf("\n");
 99 
100     return Temp;
101 }
102 
103 void main()
104 {
105     Stack *S=(Stack *)malloc(sizeof(Stack));
106     int len;
107 
108     InitStack(&S);
109     len=PushStackValue(&S);
110     len=PopStackValue(&S,len);
111     len=PopStackValue(&S,len);
112     S=ScanStack(&S);
113     IsEmpty(&S);
114 }

 

运行结果:

posted @ 2014-07-29 13:09  vpoet  阅读(201)  评论(0编辑  收藏  举报