欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語言數(shù)據(jù)結(jié)構(gòu)鏈表隊列的實現(xiàn)

 更新時間:2017年07月03日 08:46:09   作者:MrSaber  
這篇文章主要介紹了C語言數(shù)據(jù)結(jié)構(gòu)鏈表隊列的實現(xiàn)的相關(guān)資料,需要的朋友可以參考下

C語言數(shù)據(jù)結(jié)構(gòu)鏈表隊列的實現(xiàn)

1.寫在前面

  隊列是一種和棧相反的,遵循先進先出原則的線性表。

  本代碼是嚴蔚敏教授的數(shù)據(jù)結(jié)構(gòu)書上面的偽代碼的C語言實現(xiàn)代碼。

  分解代碼沒有包含在內(nèi)的代碼如下:

#include <stdio.h>
#include <stdlib.h>

#define OK 1
#define ERROR 0

typedef int QElemtype;
typedef int status;

2.代碼分解

2.1對隊列和節(jié)點的結(jié)構(gòu)定義

typedef struct QNode //對節(jié)點的結(jié)構(gòu)定義
{
  QElemtype data;
  struct QNode *next;
}QNode,*QueuePtr;

typedef struct{   //對隊列的結(jié)構(gòu)定義
  QueuePtr head;
  QueuePtr rear;
}LinkQueue;

  |說明:

    1.隊列的節(jié)點首先要保存元素,其次要指引下一個元素的位置,這是實現(xiàn)線性存儲的基礎(chǔ)也是關(guān)鍵。

    2.隊列中定義了兩個節(jié)點指針,第一個 head 用來表示 隊頭,允許移除元素。與之相反的是 rear  用來表示 隊尾,允許插入元素。

    3.為什么這么定義?

2.2 初始化和回收隊列

status initQueue(LinkQueue* que) //初始化隊列
{
  que->head=que->rear=(QueuePtr)malloc(sizeof(QNode));
  if(!que->head) //這段代碼對隊列里面的用戶自定義數(shù)據(jù)類型進行了初始化
    return ERROR;
  return OK;
}
status destoryQueue(LinkQueue* que) //回收隊列
{
  while(que->head)
  {
    que->rear = que->head->next;
    free(que->head);
    que->head=que->rear;
  }
  return OK;
}

  |說明:

    1.初始化很簡單,就是為隊列內(nèi)的兩個重要節(jié)點分配空間。

    2.隊列的回收,思路很巧妙

 循環(huán)條件是  隊列的隊頭節(jié)點 head 存在
    {
      此處rear起到臨時變量的作用,不斷指向head->next的同時,釋放head。這樣處理可以干凈的把包含頭節(jié)點在內(nèi)的隊列清理干凈。
 
     }

2.3 添加和刪除元素

status enQueue(LinkQueue* que,QElemtype e)
{
  QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
  if(!p) //若未能申請到空間,便退出
    return ERROR;
  p->data=e;
  p->next=NULL;

  que->rear->next = p;
  que->rear=p;
  return OK;
}

status delQueue(LinkQueue* que,QElemtype *t)
{
  if(que->rear==que->head)
    return ERROR; //隊列為空

  QueuePtr p = que->head->next;
  *t=p->data;

  que->head->next=p->next;
  if(que->rear==p) //這個判斷是 確保在清空隊列的時候,讓rear指針歸位。
    que->rear=que->head;
  free(p);
  return OK;
}

  |說明:

    1.添加元素的思路:新建一個節(jié)點,并給其賦值(data,next)。讓隊列的尾部相接此節(jié)點,同時更新尾部節(jié)點。

    2.刪除元素的思路:首先判斷節(jié)點是否為空?然后用臨時節(jié)點從隊頭獲取到第一個節(jié)點,即head->next,(我們的head節(jié)點并不保存元素),獲取其地址后,更新隊頭節(jié)點所指的第一個節(jié)點獲取值后釋放該地址空間。

2.4 遍歷隊列和測試方法

status viewQueue(LinkQueue* que)
{
  if(que->rear == que->head)
    return ERROR;
  
  QueuePtr p =que->head->next;
  while(p)
  {
    printf("val:%d",p->data);
    p=p->next;
  }
  return OK;
}

int main(int argc, char **argv)
{
  LinkQueue myQueue;
  initQueue(&myQueue);
  for(int i=1;i<=5;i++)
    enQueue(&myQueue,i);
  viewQueue(&myQueue);
  
  QElemtype a;
  for(int i=0;i<5;i++)
  {
    delQueue(&myQueue,&a);
    printf("%d\n",a);
  }
  destoryQueue(&myQueue);
  printf("fuck !");  
  return 0;
}

相關(guān)文章

最新評論