C语言中栈的两种实现方法详解
程序员文章站
2022-03-13 11:53:34
目录一、顺序栈#include#include#define maxsize 64//定义栈typedef struct{int data...
一、顺序栈
#include<stdio.h> #include<stdlib.h> #define maxsize 64 //定义栈 typedef struct { int data[maxsize]; int top; }sqstack,*sqslink; //设置栈空 void clearstack(sqslink s) { s->top=-1; } //判断栈空 int emptystack(sqslink s) { if (s->top<0) return 1; else return 0; } //进栈 int push(sqslink s, int x) { if (s->top>=maxsize-1) return 0; else { s->top++; s->data[s->top]=x; return 1; } } // 出栈 int popstack(sqslink s) { int n; if (emptystack(s)>0) return null; else { n=s->data[s->top]; s->top--; return n; } } void main() { sqslink s1; s1 =(sqslink)malloc(sizeof(sqstack)); clearstack(s1); printf("%d\n",s1->top); for(int i=0; i<=10;i++) { push(s1, i); printf("%d is pushed into stack\n",i); } printf("top is point to %d\n",s1->top); printf("\n"); int n; n = popstack(s1); printf("number %d is poped\n",n); printf("top is point to %d\n",s1->top); }
二、链式栈
#include<stdio.h> #include<stdlib.h> typedef struct node { int data; struct node * next; }snode,*slink; struct node { slink i; slink n; }; // 清空栈 void clearstack(slink top) { top=null; } //判断栈是否为空 int emptystack(slink top) { if (top==null) return 1; else return 0; } // 进栈 slink push(slink top, int x) { slink node = null; node = (slink)malloc(sizeof(snode)); node->data = x; node->next = top; top = node; printf("*************************\n"); printf("%d",top->data); printf("*************************\n"); return top; } // 出栈 struct node pop(slink top) { slink node = null; struct node result; if (emptystack(top)) { result.i=node; } else { int n; node = top; top = node->next; result.i = top; result.n = node; return result; } } void main() { slink top_ = null; for(int i =0; i<10;i++) { top_ = push(top_, i); printf("%d is pushed in to the stack\n",i); } int e; e = top_->data; printf("top is pointint to %d\n",e); printf("\n"); printf("\n"); printf("\n"); slink node =null; printf("*************************\n"); struct node result = pop(top_); if ((result.i)!=null) { top_ = result.i; node = result.n; e = top_->data; printf("top is pointint to %d\n",e); int e_node; e_node = node->data; printf("the node poped 's data is pointint to %d\n",e_node); free(node); } else { printf("stack is empty"); } }
总结
本篇文章就到这里了,希望能给你带来帮助,也希望您能够多多关注的更多内容!