簡體   English   中英

如何使用鏈接列表正確實現隊列

[英]How to correctly implement queue with using Linked list

我目前正在做作業。 在我的程序中,我不得不使用隊列,所以我寫了一個帶有鏈表的隊列。 但這似乎不喜歡我的語法。

所以我有結構

  typedef struct Node{
  pthread_t thread;
  int threadID;
  int securityMode;  // nTS = 1, S = 2, U = 3
  //int cluseterHalf;  //either 1st or 2nd
  struct NODE *next;
  int executionTime;
  int isLast;
}NODE;
typedef NODE *Link;

這就是我嘗試入隊的地方。

void Enqueue(Link node, Link *Queue){
  Link previous = NULL;
  Link current = *Queue;
  while (current->isLast){
    previous = current;
    current = current->next;
  }
  if(previous == NULL){
    node->next = current;
    *Queue = node;
  }
  else{
    previous->next = node;
    node->next = current;
  }
}

我試圖稍微更改代碼,但出現此錯誤。

Cluster.c:162:13: warning: assignment from incompatible pointer type
[enabled by default]
     current = current->next;
             ^
Cluster.c:165:16: warning: assignment from incompatible pointer type [enabled by default]
     node->next = current;
                ^
Cluster.c:169:20: warning: assignment from incompatible pointer type [enabled by default]
     previous->next = node;
                    ^
Cluster.c:170:16: warning: assignment from incompatible pointer type [enabled by default]
     node->next = current;

我試圖看一些類似於我的stackoverflow問題。 1) 問題 1

所以我做了很多邏輯和非邏輯的嘗試。 我嘗試編寫node-> next =&current,因為next是一個指針,它將獲取地址值。 但這沒用:(我也嘗試做對立*(node-> next)= current

我終於找到了適合我的選項,但是我不確定是否正是我想要的。 我當時以為我必須具有結構NODE * next,但是如果我接下來將NODE * next更改為NODE,那么我不會得到那些錯誤。 但是我得到了不同的結果:

Cluster.c:25:15: error: field ‘next’ has incomplete type
   struct NODE next;

您能告訴我如何解決此問題嗎? 謝謝!

嘗試更改struct NODE *next; struct Node *next; 確定你的結構

編輯:

查看更多代碼,我認為您在指針分配方面遇到了一些問題。 例如,我認為Link current = *Queue; 將僅分配Queue數據,而不分配地址,因此您無法訪問“內部”。 同樣的問題可能是以前的。

另外,我不太了解Link的用途,您可以只使用NODE

發布的代碼在維護時會帶來很多問題。 另外,代碼包含一些混亂的區域,這些區域使理解/調試變得不必要地困難。 有意義的變量名也有很大幫助。 建議:

struct Node
{
    pthread_t thread;
    int threadID;
    int securityMode;  // nTS = 1, S = 2, U = 3
    //int cluseterHalf;  //either 1st or 2nd
    struct Node *next;
    int executionTime;
    // notice removal of unneeded field isLast
};


void Enqueue(struct Node *newNode, struct Node **Queue)
{
    struct Node *current = *Queue;

    newNode->next = NULL;

    if(NULL == current)
    { // then handle special case of empty linked list
        *Queue = newNode;
    }

    else
    { // else, some nodes already in linked list
        // loop to end of linked list
        while (NULL != current->next)
        {
            // step to next node in linked list
            current = current->next;
        } // end while

        // add node to end of linked list
        current->next = newNode;
    } // end if
} // end function: Enqueue

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM