1. 程式人生 > >佇列的陣列和連結串列實現

佇列的陣列和連結串列實現

1.佇列是先入先出額資料結構,它的實現可以用陣列,也可以用連結串列。用陣列實現連結串列時,需要預先分配陣列的大小,用frontrear下標分別表示隊頭元素下標和隊尾元素下標,插入一個元素時,使隊尾的下標rear1,刪除一個元素時,front下標加1,判斷是否為空的佇列只要判斷frontrear是否相等。佇列的插入操作可表示為

# include <stdio.h>
# include <stdlib.h>
# define Maxsize  100
struct queue 
{
	int front;
	int rear;
	int q[Maxsize];
};

int main()
{   
	void initialqueue(queue*);
	void push(queue *,int);
	int pop(queue*);
	int isempty(queue*);
	int isfull(queue*);
	queue p;
	initialqueue(&p);
	push(&p,1);
	push(&p,2);
	push(&p,3);
    printf("%d\n",isempty(&p));
	printf("%d\n",pop(&p));

	system("pause");
return 0;
}

void initialqueue(queue *p)
{
	p->front=p->rear=0;
}
int isfull(queue *p)
{
	return p->rear==p->front+Maxsize-1;
}

int isempty(queue *p)
{
	return p->front==p->rear;
}
void push(queue* p,int x)
{
if(isfull(p))
{
	printf("queue is full\n");
	exit(-1);
}
p->q[p->rear++]=x;
}

int pop(queue *p)
{
if(isempty(p))
{
printf("queue is empty\n");
exit(-1);
}
return p->q[p->front++];

}

 2.連結串列實現佇列

用連結串列實現佇列,需要定義節點結構體儲存節點的值和指標,另外還要定義頭指標和尾指標,分別指向隊頭和隊尾,插入元素的操作可以表示為

                                    

# include <stdio.h>
# include <stdlib.h>
struct node
{
int num;
node *next;
};
typedef struct 
{
	node *front;
	node *rear;
}link;
int main()
{
	void initialqueue(link p);
	link push(link,int);
	int pop(link);
	int isempty(link);
	int isfull(link);
	link p={0,0};
	initialqueue(p);
	p=push(p,1);
	p=push(p,2);
	p=push(p,3);
	printf("%d\n",pop(p));
	system("pause");
return 0;
}

void initialqueue(link p)
{
p.front=p.rear=0;
}
int isempty(link p)
{
	return p.front==NULL&&p.rear==NULL;
}

link push(link p,int x)
{
	node *t=(node *)malloc(sizeof(node));
	t->num=x;
	t->next=NULL;
if(isempty(p))
{
	p.front=p.rear=t;	
}
else
{
	p.rear->next=t;	
	p.rear=t;
}
return p;
}

int pop(link p)
{
	int temp;
	node *t;
if(isempty(p))
{
printf("queue is empty\n");
exit(-1);
}
if(p.front!=p.rear){
temp=p.front->num;
t=p.front;
p.front=p.front->next;
free(t);
}
else
{
temp=p.front->num;
t=p.front;
p.front=p.rear=NULL;
free(t);
}
return temp;
}