數據結構-隊列基本操作

數據結構

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct node
{
    ElemType element; 
    struct node* link;   
}Node;

typedef struct queue
{
    Node* front; //注意front指向表頭結點,非頭結點,請對視頻中提供的代碼進行修改
    Node* rear; //指向尾結點
}Queue;

void EnQueue(Queue *Q, ElemType x);     /*出隊*/
void DeQueue(Queue *Q);     /*入隊*/
void Initialize_Queue(Queue * pQ);  /*初始化隊列*/
void traverse(Queue *pS);       /*遍歷*/

 int main()
 {
     Queue Q;
     Initialize_Queue(&Q);
     EnQueue(&Q, 1);
     EnQueue(&Q, 2);
     EnQueue(&Q, 3);

     traverse(&Q);

     DeQueue(&Q);

     traverse(&Q);

     DeQueue(&Q);
     DeQueue(&Q);

     traverse(&Q);

     return 0;
 }

 void Initialize_Queue(Queue * pQ)
 {
     pQ->front = (Node *)malloc(sizeof(Node));
     if(NULL == pQ->front)
     {
         printf("動態內存分配失敗!\n");
         exit(-1);
     }
     else
     {
        pQ->rear = pQ->front;
        pQ->front->link = NULL;
     }
 }

void EnQueue(Queue *Q, ElemType x)
{
      Node* p= (Node*)malloc(sizeof(Node));
	  p->element = x;
	  p->link = NULL;
	  Q->rear->link=p;
	  Q->rear=p;
     return ;
}

void DeQueue(Queue *Q)
 {     //若隊列爲空,直接返回
       if(Q->front->link ==NULL)  
       {
            return ; 
       }
       Node *p=Q->front->link;
       Q->front->link=p->link;
       free(p);
        //若出隊後,隊列爲空,則需重置rear
       if(Q->front->link==NULL)
            Q->rear=Q->front;//指向表頭結點  
 }

 void traverse(Queue *Q)
{
    Node * p = Q->front->link;
    
    while(p != NULL)
    {
        printf("%d ",p->element);
        p = p->link;
    }
    printf("\n");
    
    return ;
    
運行示例:
————————————————
1 2 3 
2 3 
➜  Desktop 

————————————————
}


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