数据结构——链队的基本使用
1.链队的定义:
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct
{
Node *front;
Node *rear;
}LinkQueue;
2.链队的初始化:

//初始化链队
int Init_LQ(LinkQueue &LQ)
{
Node *p;
p=new Node;
if(!p)
return 0;
LQ.front=LQ.rear=p; //新链队时,链队为空,front,rear,都指在第一个位置。
p->next=NULL;
return 1;
}
3.链队入队:

//链队入队
int Int_LQ(LinkQueue &LQ,int e)
{
Node *p;
p=new Node;
if(!p)
return 0;
p->data=e;
p->next=NULL;
LQ.rear->next=p;
LQ.rear=p;
return 1;
}
4.链队出队:

//链队出队
int Out_LQ(LinkQueue &LQ,int &e)
{
Node *p;
if(LQ.front==LQ.rear)
return 0;
p=LQ.front->next;
e=p->data;
LQ.front->next=p->next;
if(LQ.front->next==p)
{
LQ.front=LQ.rear;
}
free(p);
return 1;
}
将以上几部分合起来:
/*
Name: 链队的基本操作
Copyright:
Author: fengyu123
Date: 12/10/13 19:06
Description: 链队的基本操作
*/
#include <iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct
{
Node *front;
Node *rear;
}LinkQueue;
//链队入队
int Int_LQ(LinkQueue &LQ,int e)
{
Node *p;
p=new Node;
if(!p)
return 0;
p->data=e;
p->next=NULL;
LQ.rear->next=p;
LQ.rear=p;
return 1;
}
//链队出队
int Out_LQ(LinkQueue &LQ,int &e)
{
Node *p;
if(LQ.front==LQ.rear)
return 0;
p=LQ.front->next;
e=p->data;
LQ.front->next=p->next;
if(LQ.front->next==p)
{
LQ.front=LQ.rear;
}
free(p);
return 1;
}
void Print_LQ(LinkQueue &LQ) //将链队数据都输出来
{
Node *p;
p=LQ.front->next;
while(p)
{
cout<<p->data<<endl;
p=p->next;
}
}
int main()
{
LinkQueue LQ;
int e;
Init_LQ(LQ);
Int_LQ(LQ,1);
Int_LQ(LQ,2);
Int_LQ(LQ,3);
Int_LQ(LQ,4);
Print_LQ(LQ);
cout<<"*************************************"<<endl;
if(Out_LQ(LQ,e));
cout<<e<<endl;
if(Out_LQ(LQ,e));
cout<<e<<endl;
if(Out_LQ(LQ,e));
cout<<e<<endl;
if(Out_LQ(LQ,e));
cout<<e<<endl;
system("pause");
return 0;
}

浙公网安备 33010602011771号