顺序栈和链栈的初始化插入和删除

来源:互联网 发布:吉林11选5遗漏数据 编辑:程序博客网 时间:2024/06/01 09:08

栈是一种只能在线性表的一端进行插入或删除操作的线性表,它的特点是先进后出(FILO)后进先出(LIFO)

栈分为顺序栈和链栈,它们的特点分别如下:

顺序栈:用一维数组s[M]来表达,top代表栈顶,当栈是空的,top=-1,当栈是满的top=M-1。

顺序栈的定义:

typedef int ElemType; typedef struct sqstack{ElemType data[maxsize];int top;//栈当前可使用的最大容量}sqstack;
进栈:

ElemType push(ElemType x,sqstack *ss){if(ss->top==maxsize-1){printf("overflow\n");return 0;}else{ss->data[++(ss->top)]=x;return 1;}}

出栈:

<pre name="code" class="cpp">ElemType pop(sqstack *ss){if(ss->top<0){printf("underflow\n");return 0;}elsereturn ss->data[ss->top--];}


链栈:

当栈是空的top=NULL,栈是满的top-base=MAXSIZE;

定义:

typedef int datatype;typedef struct linkstack{datatype data;struct linkstack *next;}linkstack;

入栈:

void lsPush(linkstack *LS,int x){linkstack *p;p=new linkstack;p->data=x;p->next=top;top=p;}

出栈:

void lsPop(){linkstack *p;datatype value;if(top==NULL){printf("underflow\n");}else{p=top;value=p->data;top=top->next;delete p;printf("popout %d\n",value);}}

链栈的一个整体代码:

#include<time.h>#include<math.h># include <stdio.h># include <stdlib.h>typedef int datatype;typedef struct linkstack{datatype data;struct linkstack *next;}linkstack;linkstack *top;void lsPush(linkstack *LS,int x){linkstack *p;p=new linkstack;p->data=x;p->next=top;top=p;}void lsPop(){linkstack *p;datatype value;if(top==NULL){printf("underflow\n");}else{p=top;value=p->data;top=top->next;delete p;printf("popout %d\n",value);}}void initLS(linkstack *LS,int n){top=NULL;printf("输入%d个数字,以0结束",n);scanf("%d",&n);while(n!=0){lsPush(LS,n);scanf("%d",&n);}}int main(){linkstack *link;link=new linkstack;initLS(link,8);lsPop();}


0 0
原创粉丝点击