您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】——链式队列操作

2013-06-06 10:41 495 查看
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct node
{
int item;
struct node *next;
}node;

typedef struct queue
{
node *front;
node *rear;
}queue;

char getfirst()
{
char value;
value = getchar();
while(value == '\n' || value == '\t')
{
value = getchar();
while(getchar() != '\n');    //去掉多余的输入
}
while(getchar() != '\n');        //如果第一次输入正确,则去掉最后一个换行符;
return value;
}

int getint()
{
int value;
while(scanf("%d",&value) != 1)
{
printf("请输入数字;\n");
while(getchar() != '\n');
}
while(getchar() != '\n');
return value;
}

int menu()
{
int value;
printf("*************************************\n");
printf("一:入队列;\n");
printf("二:出队列;\n");
printf("*************************************\n");
value = getint();
while(value > 2 || value < 1)
{
printf("请输入1-2:\n");
value = getint();
}
return value;
}

queue *init()
{
queue *h;
node *n;
n = (node *)malloc(sizeof(node));
h = (queue *)malloc(sizeof(queue));

n->item = 0;
n->next = NULL;

h->front = n;
h->rear = n;
return h;
}

void pop(queue *h, int item_value)  //入队列  头指针指向第一个元素,尾指针指向最后一个空元素
{
node *value;
value = (node *)malloc(sizeof(node));

h->rear->item = item_value;

value->item = 0;
value->next = NULL;

h->rear->next = value;
h->rear = value;
}

void push(queue *h)   //出队列
{
if(h->rear == h->front)
{
printf("队列已经没有数据!");
}
else
{
node *temp;
int value;
temp = h->front;
h->front = h->front->next;
value = temp->item;
free(temp);
printf("%d\t",value);
}

}

void queue_out(queue *h)
{
char value;
do
{
push(h);
puts("countine?(y/n)");
value = getfirst();
while(value != 'y' && value != 'Y' && value != 'n' && value != 'N')
{
printf("请输入(y/n)\n");
value = getfirst();
}
}while(value == 'y' || value == 'Y');

}

void queue_in(queue *h)
{
int value;
char ch;
do
{
value = getint();
pop(h,value);
puts("countine?(y/n)");
ch = getfirst();
while(ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
{
printf("请输入(y/n)\n");
ch = getfirst();
}
}while(ch == 'y' || ch == 'Y');
}

int main(void)
{
queue *h;
char value;
h = init();
do
{
switch(menu())
{
case 1:queue_in(h);break;
case 2:queue_out(h);break;
}
printf("是否需要继续?(y/n)\n");
value = getfirst();
while(value != 'y' && value != 'Y' && value != 'n' && value != 'N')
{
printf("请输入(y/n)\n");
value = getfirst();
}
}while(value == 'y' || value == 'Y');
return 0;
}


队列的操作无非就是出队列,入队列;设计完队列的数据结构之后,就如同操作链表一样了;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: