栈与队列试题中的操作代码

参考资料:《算法与数据结构考研试题精析》《2018数据结构考研复习指导》,如果有误还请提出来~~~>W<

已知链队列的头尾指针分别是f和r,则将值x入队的操作序列是:

1 new(s);s->data=x;s->next=r->next;
2 r->next=s;r=s;

 

将数字e压入栈s,实现入栈操作

 1 typedef struct{
 2     int *base;int *top;
 3     int stacksize;
 4 }SqStack;
 5 int Push(SqStack s,int e){
 6     if(s.top-s.base>=s.stacksize-1){
 7         s.base=(int*)realloc(s.base,(s.stacksize+1)*sizeof(int));
 8         if(!s.base){cout}
 9         s.top=s.base+s.stacksize-1
10         s.stacksize=s.stacksize+1
11     }
12     *(++s.top)=e;
13 }

 

数组s作为两个堆栈的共享空间,请说明共享方法

 1 入栈
 2 if(top2-top1==1){cout}
 3 case 1:top1++,space[top1]=x;
 4 case 2:top2--.space[top2]=x;
 5 
 6 出栈
 7 case 1:if(top1==-1){cout}
 8     top1--;return space[top1+1]
 9 case 2:if(top2==N){cout}
10     top2++ return space[top2-1]
11 
12 栈满
13 top2-top1==1
14 栈空
15 top1==-1&&top2==N

 

循环队列的数据结构

1 typedef struct node{
2     elemtype elemcq[m];
3     int front,rear;
4 }cqnode;
5 cqnode cq;
6 cq.front=cq.rear=0;//初始
7 cq.front=cq.rear;//
8 (cq.rear+1)%m==cq.front;//

 

循环队列不设rear,改计数器count记录结点个数

 1 typedef struct node{
 2     elemtype q[m];
 3     int front,count;
 4 }cqnode;
 5 int empty(cqnode cq){
 6     if(cqnode.count==0){
 7         return 1;
 8     }
 9     return 0;
10 }
11 int Enquene(cqnode cq,elemtype x){
12     if(cqnode.count==m){cout}
13     cq.q[(cq.front+count)%m]=x;
14     count++;return 1;
15 }
16 int Del(cqnode cq){
17     if(count==0){cout}
18     x=cq.q[cq.front];
19     cq.front=(cq.front+1)%m;
20     return x;
21 }

 

循环队列带头结点和队尾指针

1 s=new(lnode);
2 s->data=x;s->next=p->next;p->next=s;
3 p=s;
4 //出队
5 if(p->next==p){cout}
6 s=p->next->next;p->next->next=s->next;
7 if(s==p)p=p->next;delete(s);

 

循环队列设rear,length记录结点个数

 1 typedef struct{
 2     elemType Q[m];
 3     int rear,length;
 4 }Sequene;
 5 Sequene cq;
 6 cq.length==0//
 7 cq.length==m//
 8 Sequene init(Sequene cq){
 9     cq.rear=0;
10     cq.length=0;
11     return cq;
12 }
13 Sequene en(Sequene cq,elemtype x){
14     if(cq.length==m) return 0;
15     else{
16         cq.rear=(cq.rear+1)%m;
17         cq.Q[cq.rear]=x;
18         cq.length++;
19     }
20     return cq;
21 }
22 elemtype De(Sequene cq){
23     if(cq.length==0) return 0;
24     else{
25         int front=(cq.rear-cq.length+1+m)%m;
26         cq.length--;
27         return cq.Q[front];
28     }
29 }

 

posted @ 2017-10-28 17:27  樱花落舞  阅读(504)  评论(0编辑  收藏  举报