数据结构----栈和队列的综合应用
来源:互联网 发布:安卓去广告软件 编辑:程序博客网 时间:2024/05/23 11:52
一.实验目的
熟悉掌握数据结构中队列的基本操作,能够结合栈与队列的结构灵活解决一些实际中问题。
二.实验题目
在许多语言现象中,常见到一种形如abcba的文字,这种文字从左到右读和从右到左读结果是一样的,这种文字就是常说的回文。设计一个程序可以判断给定的一个文字是否是回文。
考虑到栈的先进后出以及队列的后进先出,可以结合这两种结构来实现需要的功能,即将文字分别入队和入栈,然后依次输出判断是否有不相同的字符,一旦发现就证明文字不是一个回文。
三.实现提示
1.队列的主要数据结构定义如下:
- typedef struct QNode{
- char data;
- struct QNode *next;
- }QNode,*Queueptr;
- typedef struct{
- Queueptr front;
- Queueptr rear;
- }linkQueue;
2.程序的主框架如下:
- scanf("%c",&c);
- while(c!='#') {push(&s,c); EnQueue(&Q,c); scanf("%c",&c); }
- while(!(s.top==s.base))
- { pop(&s,&a); DeQueue(&Q,&b);
- if(a!=b) {printf("This isn't acycle\n");exit(0); }
- }
- printf("This is acycle\n"); return OK;
四 . 实现
- #include<stdio.h>
- #include<stdlib.h>
-
-
-
-
-
- typedef struct queue
- {
- int data;
- struct queue *next;
- }queue,*que;
-
- typedef struct
- {
- que front;
- que rear;
- }Q;
-
-
- typedef struct
- {
- int *top;
- int *base;
- int stacksize;
- }sqstack;
-
-
-
-
-
-
- void initStack(sqstack &s)
- {
- s.base=(int *)malloc(50*sizeof(sqstack));
- if(!s.base)
- printf("存储空间分配失败!\n");
- s.top=s.base;
- s.stacksize=50;
- }
-
-
-
-
- bool isEmpty(sqstack &s)
- {
- bool result=true;
- if(s.top==s.base)
- result=false;
- else
- result=true;
- return result;
- }
-
-
-
-
- void push(sqstack &s,int e)
- {
- if(s.top-s.base>=s.stacksize)
- {
- s.base=(int *)realloc(s.base,(s.stacksize+10)*sizeof(sqstack));
- s.top=s.base+s.stacksize;
- s.stacksize+=10;
- }
- *s.top++=e;
- }
-
-
-
-
- char pop(sqstack &s,int &e)
- {
- if(s.top==s.base)
- printf("栈是空的!");
- e=*--s.top;
- return e;
- }
-
-
-
-
- void initQ(Q &q)
- {
- q.front=q.rear=(queue *)malloc(sizeof(queue));
- if(!q.front)
- printf("存储空间分配失败!");
- q.front->next=NULL;
- }
-
-
-
-
- void EnQueue(Q &q,int e)
- {
- queue *p=(queue *)malloc(sizeof(queue));
- p->data=e;
- p->next=NULL;
-
- q.rear->next=p;
- q.rear=p;
- }
-
-
-
-
- char DeQueue(Q &q,int &e)
- {
- queue *p=(queue *)malloc(sizeof(queue));
- if(q.front==q.rear)
- printf("队列为空!");
- p = q.front->next;
- e = p->data;
- q.front->next=p->next;
- if(q.rear==p)
- q.rear = q.front;
- free(p);
- return e;
-
- }
-
-
- int main()
- {
- char c;
- int e,k;
- bool ss=true;
- sqstack s;
- Q q;
-
-
- initStack(s);
- initQ(q);
- printf("请输入字符,以 # 结束:\n");
- scanf("%c",&c);
- while(c!='#')
- {
- push(s,c);
- EnQueue(q,c);
- scanf("%c",&c);
- }
- while(!(s.top==s.base))
- {
- pop(s,e);
- DeQueue(q,k);
- if(e!=k)
- {
- printf("This isn't a cycle!\n");
- exit(0);
- }
- }
- printf("This is a cycle!\n");
- system("PAUSE");
- return 0;
- }