全部代码

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <assert.h>
  4 
  5 typedef struct node
  6 {
  7     int nValue;
  8     struct node *pNext;
  9 }MyStack;
 10 
 11 typedef struct node2
 12 {
 13     int nCount;
 14     MyStack *pTop;
 15 }Stack;
 16 
 17 void s_Init(Stack **ppStack)
 18 {
 19     assert(ppStack != NULL);
 20 
 21     *ppStack = (Stack *)malloc(sizeof(Stack));
 22     if(NULL == *ppStack)
 23     {
 24         printf("栈空间分配失败!\n");
 25         exit(-1);
 26     }
 27     (*ppStack)->nCount = 0;
 28     (*ppStack)->pTop = NULL;
 29 }
 30 
 31 void s_Push(Stack *pStack, int nNum)
 32 {
 33     MyStack *pTemp = NULL;
 34 
 35     assert(pStack != NULL);
 36 
 37     //临时节点开辟空间
 38     pTemp = (MyStack *)malloc(sizeof(MyStack));
 39     if(NULL == pTemp)
 40     {
 41         printf("临时节点空间分配失败!\n");
 42         exit(-1);
 43     }
 44     pTemp->nValue = nNum;
 45     pTemp->pNext = NULL;
 46 
 47     //头添加
 48     //临时节点的下一个是头节点
 49     pTemp->pNext = pStack->pTop;
 50     //新节点是新栈顶
 51     pStack->pTop = pTemp;
 52 
 53     //更新栈内元素
 54     ++pStack->nCount;
 55 }
 56 
 57 int s_Pop(Stack *pStack)
 58 {
 59     int nNum;
 60     MyStack *pDel = NULL;
 61 
 62     assert(pStack!=NULL && pStack->pTop!=NULL);
 63 
 64     //标记  要删除的节点
 65     pDel = pStack->pTop;
 66     nNum = pStack->pTop->nValue;
 67     //栈顶指针下移
 68     pStack->pTop = pStack->pTop->pNext;
 69     //释放空间
 70     free(pDel);
 71     pDel = NULL;
 72 
 73     //更新栈内元素
 74     --pStack->nCount;
 75 
 76     return nNum;
 77 }
 78 
 79 void s_Clear(Stack *pStack)
 80 {
 81     assert(pStack!=NULL && pStack->pTop!=NULL);
 82 
 83     while(pStack->nCount != 0)
 84     {
 85         s_Pop(pStack);
 86     }
 87 }
 88 
 89 void s_Destroy(Stack **ppStack)
 90 {
 91     assert(ppStack!=NULL && *ppStack!=NULL && (*ppStack)->pTop!=NULL);
 92 
 93     s_Clear(*ppStack);
 94     free(*ppStack);
 95     *ppStack = NULL;
 96 }
 97 
 98 int s_GetCount(Stack *pStack)
 99 {
100     assert(pStack!=NULL);
101 
102     return pStack->nCount;
103 }
104 
105 MyStack *s_GetTop(Stack *pStack)
106 {
107     assert(pStack!=NULL && pStack->pTop!=NULL);
108 
109     return pStack->pTop;
110 }
111 
112 int s_IsEmpty(Stack *pStack)
113 {
114     assert(pStack!=NULL);
115 
116     return 0==pStack->nCount ? 1:0;
117 }
118 
119 int main(void)
120 {
121     Stack *pStack = NULL;
122 
123     //初始化
124     s_Init(&pStack);
125 
126     //添加
127     s_Push(pStack, 10);
128     s_Push(pStack, 20);
129 
130     //弹出
131     printf("%d\n", s_Pop(pStack));
132     printf("%d\n", s_Pop(pStack));
133 
134     //s_Clear(pStack);
135     //s_Destroy(&pStack);
136 
137     return 0;
138 }

 

posted @ 2017-10-31 21:11  c&z  阅读(188)  评论(0编辑  收藏  举报