|

楼主 |
发表于 2020-10-27 20:11:50
|
显示全部楼层
- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #define OK 1
- #define ERROR 0
- #define OVERFLOW -2
- #define MAXSIZE 20
- typedef int Status;
- typedef struct QNode{
- int data;
- struct QNode *next;
- }QNode,*QueuePtr;
- typedef struct{
- QueuePtr front;
- QueuePtr rear;
- }LinkQueue;
- Status InitQueue(LinkQueue &Q)
- {
- Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
- if(!Q.front)exit(OVERFLOW);
- Q.front->next=NULL;
- return OK;
- }
- Status EnQueue(LinkQueue &Q,int e)
- {
- QueuePtr p;
- p=(QueuePtr)malloc(sizeof(QNode));
- if(!p)exit(OVERFLOW);
- p->data=e;
- p->next=NULL;
- Q.rear->next=p;
- Q.rear=p;
- return OK;
- }
- Status DeQueue(LinkQueue &Q,int e)
- {
- QueuePtr p;
- if(Q.front==Q.rear)
- {
- return ERROR;
- }
- p=Q.front->next;
- e=p->data;
- Q.front->next=p->next;
- if(Q.rear==p)
- {
- Q.rear=Q.front;
- }
- free(p);
- return OK;
- }
- Status GetHead(LinkQueue Q)
- {
- if(Q.front=Q.rear)
- {
- return Q.front->next->data;
- }
- }
- void Print(LinkQueue Q)
- {
- printf("\n队列为:");
- QueuePtr p;
- p=Q.front->next;
- while(p && Q.front!=Q.rear)
- {
- printf("%d ",p->data);
- p=p->next;
- }
- }
- int Compare(LinkQueue &Q,int position,int length)
- {
- QueuePtr p;
- int a,b;
- a=Q.front->next->data;//队头的元素
- p=Q.front->next;//依次指向队列中的所有元素
- b=p->data;
- while(p!=NULL && Q.front!=Q.rear)
- {
- if(a>=b)//如果队头元素大就往后移动p指针
- {
- p=p->next;
- b=p->data;
- }
- else if(a<b)//如果有大于队头元素的就把队头元素删除并添加到队尾再退出函数
- {
- DeQueue(Q,a);
- EnQueue(Q,a);
- return length;
- }
- }
- return position;
- }
- int main()
- {
- LinkQueue Q;
- InitQueue(Q);
- int num[MAXSIZE],length;
- printf("输入队列长度:");
- scanf("%d",&length);
- printf("\n输入队列:");
- for(int i=0;i<length;i++)
- {
- scanf("%d",&num[i]);
- EnQueue(Q,num[i]);
- }
- Print(Q);
-
- int position;
- printf("\n\n输入需要打印的任务的位置:");
- scanf("%d",&position);
-
- for(int i=0;i<position-1;i++)//把指定位置的任务移到队头
- {
- DeQueue(Q,num[i]);
- EnQueue(Q,num[i]);
- }
- Print(Q);
-
- int time=Compare(Q,position,length);
- printf("\n花费时间为:%d",time);
- Print(Q);
- }
复制代码 |
|