当前位置:   article > 正文

408王道打卡表---(1)栈,队列的应用_王道数据结构打卡表

王道数据结构打卡表

1.定义顺序存储的栈

  1. #define Maxlen 50
  2. typedef struct{
  3. int data[Maxlen];
  4. int top; //标识栈顶元素
  5. }SqStack;

1.1 入栈操作

  1. bool PushStack(int e, SqStack S){
  2. if(S.top<Maxlen)
  3. {
  4. S.data[++S.top]=e;
  5. return true;
  6. }
  7. return false;
  8. }

1.2 出栈操作

  1. bool PopStack(int &x, SqStack S){
  2. if(S.top!=-1){
  3. x=S.data[S.top--];
  4. return true;
  5. }
  6. return false;
  7. }

 1.3  顺序栈判空

  1. bool IsEmpty(SqStack S)
  2. {
  3. if(S.top==-1)
  4. return true;
  5. return false;
  6. }

1.5.  顺序栈判满

  1. bool IsFull(SqStack S)
  2. {
  3. if(S.top==Maxlen-1)
  4. return true;
  5. return false;
  6. }

2.定义链式存储的栈(栈顶在链尾)

  1. typedef struct StackNode{
  2.     int data;
  3. struct StackNode *next;
  4. int top;
  5. }*LinkStack;//链栈的定义

2.1.链栈初始化

  1. bool InitStack(LinkStack &S) {
  2. S=NULL;
  3. return true;
  4. }

2.2.链栈判空 

  1. bool IsEmptyLinkStack(LinkStack &S)
  2. {
  3. if(S==NULL)
  4. return true;
  5. else
  6. return false;
  7. }

2.4.进栈(插入操作)

  1. bool PushStack(int x, LinkStack &S)
  2. {
  3. StackNode *p=(StackNode*)malloc(sizeof(StackNode));
  4. p->data=x;
  5. p->next=S;
  6. S=p;
  7. return true;
  8. }

2.5 出栈(删除操作)

  1. bool PopStack(int &x,LinkStack &S)
  2. {
  3. if(S!=NULL)
  4. {
  5. x=S->data;
  6. StackNode *p=S;
  7. S=S->next;
  8. free(p);
  9. return true;
  10. }
  11. return false;
  12. }

3.1用双向链表来实现栈
1.  push压栈就是顺序添加 先找到要添加位置的前一个位置,让前一个位置的节点 
2.  pop出栈 先找到最后一个节点 让其自我删除 双向链表可以自我删除 不用找到要删除位置的前一个节点

  1. //定义链表节点
  2. #define MaxStack 50
  3. typedef struct StackNode {
  4. struct StackNode* next;
  5. struct StackNode* prev;
  6. int top;
  7. int data;
  8. }STNode;

3.1.栈的判空操作

  1. bool IsLinkStackEmpty(STNode &S)
  2. {
  3. if(S==NULL)
  4. return true;
  5. return false;
  6. }

3.2.栈的判满操作

  1. bool IsLinkStackFull(&STNode &S)
  2. {
  3. if(S->top==MaxStack)
  4. {
  5. return true;
  6. }
  7. return false;

3.3.入栈操作

  1. bool PushStack(STNode &S,int x)
  2. {
  3. if(!IsLinkStackFull(&S))
  4. return false;
  5. STNode *p= (STNode*)malloc(sizeof(STNode));
  6. p->data=x;
  7. p->top=S->top+1;
  8. S->next=p;
  9. p->next=NULL;
  10. p->prev=S;
  11. S=p;
  12. return true;
  13. }

3.4.出栈操作

  1. bool PopStack(STNode &S,int &x)
  2. {
  3. if(!IsLinkStackEmpty(&S))
  4. return false;
  5. STNode *p= S;
  6. x=p->data;
  7. S=S->prev;
  8. S->next=NULL;
  9. free(p);
  10. return true;
  11. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/909324
推荐阅读
相关标签
  

闽ICP备14008679号