链队列的基本操作
用结构体形成链,进行队列的基本操作
代码:
#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct queue
{
ElemType data;
struct queue *next;
} queue;
queue *head, *end;
void seqlistinit();
void push();
void printmenu();
ElemType pop();
ElemType gettop();
int isempty();
void destroy();
void printmenu()
{
int m;
printf("--------------------\n");
printf("please input your operation:\n", &m);
printf("1.push\n");
printf("2.pop\n");
printf("3.get top\n");
printf("4.break and destroy\n");
printf("--------------------\n");
}
void seqlistinit()
{
head = (queue *)malloc(sizeof(queue));
head->next = NULL;
end = head;
}
int isempty()
{
if (head == end)
return 1;
else
return 0;
}
void push()
{
int m;
queue *q;
q = (queue *)malloc(sizeof(queue));
q->next = NULL;
printf("please input the number you want\n");
scanf("%d", &m);
q->data = m;
end->next = q;
end = q;
int k = end->data;
printf("%d insert Succss!\n", k);
}
ElemType pop()
{
if (isempty())
{
printf("queue is empty\n");
return 0;
}
else
{
queue *q = head->next;
head->next = q->next;
ElemType a = q->data;
printf("%d pop success!\n", a);
head->next = q->next;
if (end == q)
end = head;
free(q);
return a;
}
}
ElemType gettop()
{
if (isempty())
{
printf("queue is empty\n");
return 0;
}
else
{
ElemType a = head->next->data;
printf("%d is the top data!\n", a);
return a;
}
}
void destroy()
{
queue *q;
while (end != head)
{
q = head;
head = head->next;
free(q);
}
printf("destroy successful\n");
}
int main()
{
seqlistinit();
int n, m;
int flag = 1;
while (flag)
{
printmenu();
scanf("%d", &m);
switch (m)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
gettop();
break;
case 4:
destroy();
flag = 0;
break;
default:
printf("please input again\n");
break;
}
}
}