数据结构习题学习笔记(The Fifth Day)

来源:互联网 发布:多益网络客户端下载 编辑:程序博客网 时间:2024/05/16 09:09
 Q1:  用单链表实现队列,并令 front=rear=NULL 表示队列为空,编写实现队列的如下五种运算的函数:
makenull:将队列置成空队列;
front:返回队列的第一个元素;
enqueue:把元素 x 插入到队列的后端;
dequeue:删除队列的第一个元素;
empty:判定队列是否为空。
MyView:道理简单,实现起来不容易.
注:使用LCC的IDE,好用并且方便.
CODE:
1,queue.h (队列头文件)
#include <stdio.h>
#include 
<stdlib.h>

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

typedef 
struct{
    QueuePtr front;
//对头指针
    QueuePtr rear;//队尾指针
}
LinkQueue;//队列定义符号

/*构造队列*/
LinkQueue
* makeQueue(){
    LinkQueue 
*= (LinkQueue *) malloc(sizeof(LinkQueue));
    
if(!Q)printf("Q:OVERFLOW ");//存储分配失败
    else{
    Q
->rear=NULL;
    Q
->front= NULL;
    }

    
return Q;
}


//构造节点
QueuePtr makeNode(int i){
    QueuePtr N 
= (QueuePtr)malloc(sizeof(QNode));
    
if(!N)printf("Node:OVERFLOW ");//存储分配失败
    else{
    N
->data=i;
    N
->next=NULL;
    }

    
return N;
}


//判断队列是否为空
int isEmpty(LinkQueue *Q){

    
if(Q->front == NULL)
        
return 1;
    
else
        
return 0;
}


//将队列置空
void makeNull(LinkQueue *Q){
    
if(!isEmpty(Q))
       printf(
"错误:队列为空!");
    
else{
       Q
->rear=NULL;
       Q
->front= NULL;
    }

}


//删除队列第一个元素
void deQueue(LinkQueue *Q){
    
if(isEmpty(Q))
       printf(
"错误:队列为空! ");
    
else{
       QueuePtr p;
       p 
= Q->front;
       Q
->front = p->next;
       free(p);
    }

}


/*返回队列的第一个元素*/
int front(LinkQueue *Q)
{
    
int x;
    
if(!isEmpty(Q) && Q->front!=NULL)
        x
=(Q->front->data);
    
return x;
}


/*把元素x插入到队列右端*/
void enqueue(LinkQueue *Q,int e)
{
    QueuePtr p 
= makeNode(e);

         
if ( !isEmpty(Q))    //队列不为空,直接链接到队列尾部
          {
            Q
->rear->next = p;
            Q
->rear = p;
          }

          
else
          
{    //队列为空
             Q->front = p;
             Q
->rear = p;
          }


}


/*打印链表*/
void print(LinkQueue *Q){
    
if(!isEmpty(Q)){//判断队列是否为空
          QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
          
if(!p)printf("Node:OVERFLOW ");//存储分配失败
          else{
               printf(
"队列为:");
               p
=Q->front;
               
do
               
{
                  printf(
"%d",p->data);
                  
if((p->next)!=NULL){
                     p
=p->next;
                  }

                  
else break;
                  printf(
",");
               }
while(1);
               printf(
" ");
          }

     }

     
else
         printf(
"错误:检测到队列为空,无法打印! ");
}

2,测试代码
#include <stdio.h>
#include 
"queue.h"



void main()
{

    LinkQueue 
*Queue = makeQueue();

    print(Queue);
    enqueue(Queue,
3);
    enqueue(Queue,
4);
    enqueue(Queue,
5);
    enqueue(Queue,
6);


    print(Queue);
    deQueue(Queue);
    print(Queue);

}

 

RUN:

Good Luck……

原创粉丝点击