Most feature of Queue is "first in first out",the following code can construct a Queue using Linear List ,many issues could be solved by its thought.a simple and interesting problem within the code.XD
// STACK.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<malloc.h>
struct queue{
int data;
queue *next;
};
struct{
queue *front;
queue *rear;
}q;
int initqueue()
{
q.front=NULL;
queue *h1=(queue *)malloc(sizeof (queue));
q.rear=h1;q.rear->data=0;
return 0;
}
int queuein(int data){
queue *h1=(queue *)malloc(sizeof (queue));h1->data=data;
if(h1==NULL){puts("malloc failure!");}
if(q.front==NULL){q.front=h1;h1->next=q.rear;q.rear->next=q.front;return 0;}
h1->next=q.front;
q.front=h1;
q.rear->next=q.front;
return 0;
}
int queueout(){
queue *h1=q.front,*h2=q.rear;
while(h1->next!=q.rear) h1=h1->next;
h1->next=h2->next;
q.rear=h1;
free(h2);
return 0;
}
void display(){
queue *h1=q.front;
puts("--------------------------");
while(h1!=q.rear){printf("%d\t",h1->data);h1=h1->next;}
}
int main(int argc, char* argv[])
{ initqueue();
for(int i=1;i<11;i++)
{
queuein(i);
}
display();
/*报数问题:从编号1开始报数,数到3的人出列;
下一个又从1开始数,数到3又出列,如此反复,
直到全部出列;给出出列顺序*/
puts("报数问题:\n");
while(q.front!=q.rear)
{
for(i=0;i<2;i++){queueout();queuein(q.rear->data);}
queueout();
printf("%d\t",q.rear->data);
}
/*杨辉三角*/
puts("杨辉三角:\n");
int k;
initqueue();
queuein(1);
display();putchar('\n');
queuein(1);
display();putchar('\n');
queueout();
for(i=1;i<7;i++)
{
for(int j=0;j<i;j++)
{
k=q.rear->data;
queueout();
queuein(k+q.rear->data);
}
queuein(1);
display();printf("%d\t",q.rear->data);
putchar('\n');
}
return 0;
}