數據結構習題學習筆記(The Fifth Day)

 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……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章