数据结构-栈

Posted hujianglang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构-栈相关的知识,希望对你有一定的参考价值。

  1 #include <stdio.h>
  2 #include <malloc.h>
  3 #include <stdlib.h>
  4 
  5 typedef struct Node
  6 {
  7     int data;
  8     struct Node *pNext;
  9 }NODE,*PNODE;
 10 
 11 typedef struct Stack
 12 {
 13     PNODE pTop;
 14     PNODE pBottom;
 15 }STACK,*PSTACK;
 16 
 17 void init(PSTACK);
 18 void push(PSTACK, int);
 19 bool pop(PSTACK, int*);
 20 void clear(PSTACK pS);
 21 
 22 int main(void)
 23 {
 24     int val;
 25     STACK S;
 26     init(&S);
 27     push(&S,1);
 28     push(&S,2);
 29     pop(&S,&val);
 30     traverse(&S);
 31     clear(&S);
 32     return 0;
 33 }
 34 
 35 void init(PSTACK pS)
 36 {
 37     pS->pTop = (PNODE)malloc(sizeof(NODE));
 38     if (NULL == pS->pTop)
 39     {
 40         printf("malloc fail!");
 41         exit(-1);
 42     }
 43     else
 44     {
 45         pS->pBottom = pS->pTop;
 46         pS->pTop->pNext = NULL;
 47     }
 48 }
 49 
 50 
 51 void push(PSTACK pS, int val)
 52 {
 53     PNODE pNew = (PNODE)malloc(sizeof(NODE));
 54     if (NULL != pNew)
 55     {
 56         pNew->data = val;
 57         pNew->pNext = pS->pTop;
 58         pS->pTop = pNew;
 59     }
 60     return;
 61 }
 62 
 63 void traverse(PSTACK pS)
 64 {
 65     PNODE p = pS->pTop;
 66     while (p != pS->pBottom)
 67     {
 68         printf("%d", p->data);
 69         p=p->pNext;
 70     }
 71     printf("
");
 72 }
 73 
 74 bool empty(PSTACK pS)
 75 {
 76     if (pS->pBottom == pS->pTop)
 77     {
 78         return true;
 79     }
 80     else
 81     {
 82         return false;
 83     }
 84 }
 85 
 86 bool pop(PSTACK pS, int *pVal)
 87 {
 88     if (empty(pS))
 89     {
 90         return false;
 91     }
 92     else
 93     {
 94         PNODE r = pS->pTop;
 95         *pVal = r->data;
 96         pS->pTop = r->pNext;
 97         free(r);
 98         r = NULL;
 99         return true;
100     }
101 }
102 
103 //清空
104 void clear(PSTACK pS)
105 {
106     if (empty(pS))
107     {
108         return;
109     }
110     else
111     {
112         PNODE p = pS->pTop;
113         PNODE q = NULL;
114         while (p != pS->pBottom)
115         {
116             q = p->pNext;
117             free(p);
118             p = q;
119         }
120     }
121     pS->pTop = pS->pBottom;
122 }

 

以上是关于数据结构-栈的主要内容,如果未能解决你的问题,请参考以下文章

方法与对象内存分析

Android Studio - 带回栈的导航抽屉

使用callstack在C中实现栈数据结构?

VSCode自定义代码片段5——HTML元素结构

VSCode自定义代码片段5——HTML元素结构

VSCode自定义代码片段5——HTML元素结构