链栈的相关操作

  1 /*
  2 2012年11月23日9:10:12
  3 链栈的基本操作 
  4 InitStack    初始化链栈
  5 */
  6 
  7 
  8 #include<stdio.h>
  9 #include<stdlib.h>
 10 
 11 
 12 
 13 //////////定义结构体//////////////////
 14 typedef struct Node
 15 {
 16     struct Node *pNext;
 17     int data;
 18 }NODE,*PNODE;
 19 
 20 typedef struct Stack            
 21 {
 22     PNODE pTop;                 
 23     int count;     
 24 }LinkStack,*PLinkStack;
 25 
 26 
 27 
 28 ////////////函数声明//////////////////////
 29 void InitStack(PLinkStack);
 30 void Push(int val,PLinkStack pS);
 31 void Traverse(PLinkStack pS);
 32 void Pop(PLinkStack pS);
 33 
 34 
 35 /////////////主函数///////////////////
 36 int main(void)
 37 {
 38     LinkStack S;
 39     InitStack(&S);
 40     Push(3,&S);
 41     Push(2,&S);
 42     Push(4,&S);
 43     Push(5,&S);
 44     Traverse(&S);
 45     Pop(&S);
 46     Traverse(&S);
 47     return 0;
 48 }
 49 
 50 
 51 
 52 ///////////初始化链栈//////////////////
 53 void InitStack(PLinkStack pS)
 54 {
 55     
 56     pS->pTop = (PNODE)malloc(sizeof(NODE));
 57     if(NULL == pS->pTop)
 58     {
 59         printf("分配内存失败\n");
 60         exit(-1);
 61     }
 62     else
 63     {
 64         pS->pTop->pNext = NULL;
 65         pS->count = 0;
 66     }
 67 }
 68 
 69 
 70 
 71 ////////////入栈///////////////
 72 void Push(int val,PLinkStack pS)
 73 {
 74     PNODE pNew;
 75     pNew = (PNODE)malloc(sizeof(NODE));
 76     if(NULL == pNew)
 77     {
 78         printf("分配内存失败\n");
 79         exit(-1);
 80     }
 81     else 
 82     {
 83         pNew->data= val;
 84         pNew->pNext = pS->pTop;
 85         pS->pTop = pNew;
 86         pS->count++;
 87     }
 88 }
 89 
 90 
 91 ///////////遍历输出////////////////
 92 void Traverse(PLinkStack pS)
 93 {
 94     PNODE pTemp = pS->pTop;
 95     if(NULL == pTemp->pNext)
 96     {
 97         printf("空栈!\n");
 98     }
 99     else
100     {
101         while(NULL!=pTemp->pNext)
102         {
103             printf("%d\n",pTemp->data);
104             pTemp = pTemp->pNext;
105         }
106     }
107     return;
108 }
109 
110 
111 ////////////出栈////////////////////
112 void Pop(PLinkStack pS)
113 {
114     PNODE pTemp = pS->pTop;
115     if(NULL == pTemp->pNext)
116     {
117         printf("空栈!\n");
118     }
119     else
120     {
121         printf("出栈元素为%d\n",pTemp->data);
122         pS->pTop = pS->pTop->pNext;
123         free(pTemp);
124         pS->count--;
125         
126     }
127     
128     
129 }

 

posted @ 2012-11-23 21:43  木有Some  阅读(277)  评论(0编辑  收藏  举报