赞
踩
1.定义顺序存储的栈
- #define Maxlen 50
- typedef struct{
- int data[Maxlen];
- int top; //标识栈顶元素
- }SqStack;
1.1 入栈操作
- bool PushStack(int e, SqStack S){
- if(S.top<Maxlen)
- {
- S.data[++S.top]=e;
- return true;
- }
- return false;
- }
1.2 出栈操作
- bool PopStack(int &x, SqStack S){
- if(S.top!=-1){
- x=S.data[S.top--];
- return true;
- }
- return false;
- }
1.3 顺序栈判空
- bool IsEmpty(SqStack S)
- {
- if(S.top==-1)
- return true;
-
- return false;
- }
1.5. 顺序栈判满
- bool IsFull(SqStack S)
- {
- if(S.top==Maxlen-1)
- return true;
-
- return false;
- }
2.定义链式存储的栈(栈顶在链尾)
- typedef struct StackNode{
- int data;
- struct StackNode *next;
- int top;
- }*LinkStack;//链栈的定义
2.1.链栈初始化
- bool InitStack(LinkStack &S) {
- S=NULL;
- return true;
- }
2.2.链栈判空
- bool IsEmptyLinkStack(LinkStack &S)
- {
- if(S==NULL)
- return true;
- else
- return false;
- }
2.4.进栈(插入操作)
- bool PushStack(int x, LinkStack &S)
- {
- StackNode *p=(StackNode*)malloc(sizeof(StackNode));
- p->data=x;
- p->next=S;
- S=p;
- return true;
- }
2.5 出栈(删除操作)
- bool PopStack(int &x,LinkStack &S)
- {
- if(S!=NULL)
- {
- x=S->data;
- StackNode *p=S;
- S=S->next;
- free(p);
- return true;
- }
- return false;
- }
3.1用双向链表来实现栈
1. push压栈就是顺序添加 先找到要添加位置的前一个位置,让前一个位置的节点
2. pop出栈 先找到最后一个节点 让其自我删除 双向链表可以自我删除 不用找到要删除位置的前一个节点
- //定义链表节点
- #define MaxStack 50
- typedef struct StackNode {
- struct StackNode* next;
- struct StackNode* prev;
- int top;
- int data;
- }STNode;
3.1.栈的判空操作
- bool IsLinkStackEmpty(STNode &S)
- {
- if(S==NULL)
- return true;
- return false;
- }
3.2.栈的判满操作
- bool IsLinkStackFull(&STNode &S)
- {
- if(S->top==MaxStack)
- {
- return true;
- }
- return false;
3.3.入栈操作
- bool PushStack(STNode &S,int x)
- {
- if(!IsLinkStackFull(&S))
- return false;
- STNode *p= (STNode*)malloc(sizeof(STNode));
- p->data=x;
- p->top=S->top+1;
- S->next=p;
- p->next=NULL;
- p->prev=S;
- S=p;
- return true;
- }
3.4.出栈操作
- bool PopStack(STNode &S,int &x)
-
- {
- if(!IsLinkStackEmpty(&S))
- return false;
- STNode *p= S;
- x=p->data;
- S=S->prev;
- S->next=NULL;
- free(p);
- return true;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。