单链队列的实现

#include<iostream>

using namespace std;

typedef enum { ERROR=0, OK=1,TRUE=1, FALSE = 0 } Status;

typedef int QElemType;

typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;

typedef struct
{
QueuePtr front;//队头指针
QueuePtr rear; //队尾指针
}LinkQueue;

Status visit( QElemType e )
{
printf("e=%d\n",e);

return OK;
}

Status InitQueue( LinkQueue &Q )//构造一个空队列
{
Q.front = Q.rear =( QueuePtr )malloc ( sizeof ( QNode ));

if ( !Q .front)
exit (ERROR );
Q.rear=Q.front;
Q.front->next= NULL;

return OK;
}

Status DestroyQueue( LinkQueue &Q )//销毁队列Q
{
while ( Q.front )
{
Q.rear =Q.front ->next;
free ( Q.front );
Q.front = Q.rear;
}

return OK;
}

Status ClearQueue( LinkQueue &Q )//清空队列Q
{
QueuePtr p;
p=Q.front; //用p寄存头节点
Q.front=Q.front->next; //Q.front指向队头的第一个元素
DestroyQueue( Q );

Q.front=p; //将队头指针和队尾指针指向头结点,头结点的next域为空
Q.front->next=NULL;
Q.rear = Q.front;
return OK;
cout<<"Q.rear ->next"<<Q.rear->next<<endl;
return OK;
}

Status QueueEmpty( LinkQueue Q )//队列是否为空
{
if(( Q.front!= Q.rear )&&( Q.front->next!=NULL))
return TRUE;
else
return FALSE;
}

int QueueLength( LinkQueue Q )/*如果队列为空队列返回TRUE,否则返回FALSE*/
{
QueuePtr p;
int i;
p= Q.front->next;
for ( i= 0;p !=NULL ;i++)
p=p->next;

return i ;
}

Status GetHead( LinkQueue Q, QElemType &e )//取得队头元素
{
if ( !QueueEmpty( Q ) )
{
e = Q.front->next->data;
return OK;
}

return ERROR;

}

Status EnQueue( LinkQueue &Q, QElemType e )//插入元素e为新的队尾元素
{
QueuePtr p;
p = ( QueuePtr )malloc( sizeof ( QNode ) );
if ( !p )
exit( ERROR );
p->data = e;
p->next = NULL;
Q.rear->next = p; /*插入e,修改队尾指针*/

Q.rear = p;

return OK;
}

Status DeQueue( LinkQueue &Q, QElemType &e )//删除队头元素,用e返回
{
QueuePtr p;
if ( Q.front == Q.rear )
return ERROR;
p = Q.front->next;
e = p->data;
Q.front->next=p->next;

if ( Q.rear == p )
Q.rear =Q.front; /*若p指向队尾,删除p后Q.rear也将丢失,所以要修改Q.rear=Q.front*/
free ( p );

return OK;
}

Status QueueTraverse( LinkQueue Q, Status (*visit)( QElemType e ) )//遍历队列元素
{
QueuePtr p;
p = Q.front;
while( p!=Q.rear )
{
p=p->next;
visit(p->data);
}
return OK;
}
int main ()//测试
{
LinkQueue qu;

//int e ;
InitQueue ( qu );

for ( QElemType i = 0; i<10; i++)
EnQueue ( qu , i );
cout<<"length = "<<QueueLength( qu )<<endl;

//DeQueue( qu, e );
//cout <<"e = "<<e<<endl;
ClearQueue( qu );
cout<<"length = "<<QueueLength( qu )<<endl;
//QueueTraverse( qu , visit );

return 0 ;

}

posted on 2012-10-23 11:51  Eternal Code  阅读(130)  评论(0编辑  收藏  举报