2014-04-20 31 views
1

我嘗試使用鏈接列表來執行隊列的實現,但總是出現錯誤:賦值和賦值中的不兼容類型使得整型指針沒有強制轉換。c - 使用鏈表執行隊列

這裏是我的代碼:

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

struct QUEUE_ELEMENT{ 
int element; 
struct QUEUE_ELEMENT *next; 
}; 

int size; 
struct QUEUE_ELEMENT *head, *tail; 

void initQueue(){ 

    head = NULL; 
    tail = NULL; 
    size = 0; 

}  // void initQueue() 



int queueEmpty(void) { 

return (head == NULL && tail == NULL); 

} // int queueEmpty(void) 





int enqueue(QUEUE_ELEMENT e) { 
struct QUEUE_ELEMENT *temp; 
if (tail == NULL){ 
    tail -> next = NULL; 
    tail -> element = e; 
    head = tail; 
} 
else { 
    temp = malloc(sizeof(QUEUE_ELEMENT)); 
    tail -> next = temp; 
    temp -> element = e; 
    temp -> next = NULL; 
    tail = temp; 
} 
return size++; 

} // int enqueue(QUEUE_ELEMENT e) 





int dequeue(QUEUE_ELEMENT *e){ 
struct QUEUE_ELEMENT *temp; 
temp = malloc(sizeof(QUEUE_ELEMENT)); 

if (queueEmpty() != 0){ 
    temp = head; 
    if(temp -> next != NULL){ 
    temp = temp -> next; 
    free(head); 
    head = temp; 
    } 
    else{ 
     free(head); 
     head = NULL; 
     tail = NULL; 
    } 
} 
    return size--; 


} // int dequeue(QUEUE_ELEMENT *e) 

我修改我的代碼了很多。

爲什麼'tail - > element = e''在enqueue()中發生錯誤'賦值中的不兼容類型'?我該如何解決它?

+2

其中???發佈實際的編譯器錯誤 – yamafontes

+0

具有'size','head','tail',*和*'next'的「節點」看起來不是一個好設計。 – user2864740

+0

這個代碼有太多的錯誤,它讓我的頭部受傷...爲什麼你需要這麼多的指針來建立一個簡單的鏈表? – littleadv

回答

0

這是作業還是真正的需要?對於第一個我什麼都不會說。但如果您在實踐中需要它,最好使用已實施的解決方案。

有一個流行的風格,其中,在鏈表中,頭看起來像通常的條目,唯一區別它的就是頭指針值本身。第一個很好的例子是Linux鏈表實現(a description)。其具體細節是從其鏈接成員獲取整個入口地址的技巧。這是一個微不足道的學習,可以立即回答你的目標。

第二個很好的例子是BSD列表和隊列宏集(manpage;特別是,你可以從TAILQ宏集開始)。由於一些技巧(例如,前向指針尋址鏈接字段,但後向指針尋址整個結構),但仍然有效,這更麻煩。

我希望既能滿足你和防止重新發明輪子:)

0

您分配tail->element,這是一個int,以e這是一個QUEUE_ELEMENT。如果你想訪問e中的元素,你必須像對待尾巴那樣遵從它。 so tail->element = e->element

+0

但e不是指針。所以' - >'對e無效。 – rhea

+0

對不起,我看了一會兒的出列,然後才e.element。另一個提示是,你正在檢查tail是否爲NULL,然後試圖推斷它併爲它賦值,這是一個分段錯誤。您必須先分配內存或將其分配給另一個指針 – Willie

+0

謝謝,我已經修復它。 – rhea