3.2.3队列的链接实现

 

// DataStructTest.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream.h>
#include 
<malloc.h>

typedef 
struct linked_queue
{
    
int data;
    
struct linked_queue * next;
}
LqueueTp;
typedef 
struct queueptr
{
    LqueueTp 
* front;
    LqueueTp 
* rear;

}
QueptrTp;

//初始化.申请一个结点且不存储信息,只作为判断是否为空结点的标志
void InitQueue(QueptrTp & lq)
{
    LqueueTp 
* p=NULL;
    
while(lq.front!=NULL)
    
{
        p
=lq.front;
        lq.front
=lq.front->next;
        free(p);
    }

    lq.front
=lq.rear=NULL;
    p
=(LqueueTp *)malloc(sizeof(linked_queue));
    p
->next=NULL;
    lq.front
=lq.rear=p;
}

//入队
void EnQueue(QueptrTp & lq,int value)
{
    LqueueTp 
* p=(LqueueTp *)malloc(sizeof(linked_queue));
    p
->data=value;
    p
->next=NULL;
    
//修改队尾结点指向新的结点后,再将尾结点指向新增的结点
    lq.rear->next=p;
    lq.rear
=p;
}

//出队
int OutQueue(QueptrTp & lq,int & value)
{
    
if (lq.front==lq.rear)
    
{
        
return 0;
    }


    
//得到首节点的值.因为lq.front指向的是标志结点,所以要指向next后面的结点的data
    value=lq.front->next->data;
    
//使首结点指向下一个结点作为了标志结点,然后释放原首结点的空间
    LqueueTp * p=lq.front;
    lq.front
=lq.front->next;
    free(p);
    
return 1;
}

//判断是否为空
int EmptyQueue(QueptrTp & lq)
{
    
if (lq.front==lq.rear)
        
return 1;
    
else
        
return 0;
}

//得到队头结点的值
int GetHead(QueptrTp & lq,int & value)
{
    
if (lq.front==lq.rear)
    
{
        
return 0;
    }

    value
=lq.front->next->data;
    
return 1;
}

//显示
void Display(QueptrTp & lq)
{
    LqueueTp 
* p=lq.front->next;
    
while(p!=NULL)
    
{
        cout
<<"队列中的元素为:"<<p->data<<endl;
        p
=p->next;
    }

}


int main(int argc, char* argv[])
{
    QueptrTp lq;
    lq.front
=NULL;
    lq.rear
=NULL;
    InitQueue(lq);
    
//入队
    for(int i=1;i<20;i++)
    
{
        EnQueue(lq,i);
    }

    Display(lq);
    
//出队
    int value=0;
    OutQueue(lq,value);
    cout
<<"出队的结点值为:"<<value<<endl;
    Display(lq);
    
//
    EnQueue(lq,500);
    cout
<<endl;
    Display(lq);
    
return 0;
}

posted @ 2007-06-25 16:45  吴东雷  阅读(278)  评论(0编辑  收藏  举报