我在C中創建鏈接列表數據結構。但是,我在實現addLast函數時收到了一些奇怪的行爲。看來添加的元素在我下一次調用addLast之前不會出現。C - 鏈接列表的addLast函數的奇怪行爲
助手代碼:
typedef struct LinkedList linkedlist;
typedef int ListElement;
struct LinkedList{
ListElement data;
linkedlist *next;
};
//Initializes a list;
void CreateList(linkedlist *list, ListElement contents){
list->data = contents;
list->next = NULL;
}
//Prints the items of the list, head first.
void displayList(linkedlist *list){
printf("(%d", list->data);
linkedlist *node = list->next;
if(node == NULL){
}
else{
while(node->next != NULL){
printf(" %d", node->data);
node = node->next;
}
}
printf(")");
}
問題的代碼:
//Adds an element at the tail of the list
void addLast(linkedlist *list, ListElement forAdding){
linkedlist *node = list;
linkedlist *NewNode = (linkedlist *) malloc(sizeof(linkedlist));
//Go to the last element in the list
while(node->next != NULL){
node = node->next;
}
//Prepare the node we will add
NewNode->data = forAdding;
NewNode->next = NULL;
//Since node is pointing to the tail element, set its
//next to the NewNode---the new tail
node->next = NewNode;
}
//Special attention to this function!
void List(ListElement items[], linkedlist *list, int numItems){
int i = 0;
while(i < numItems){
addLast(list, items[i]);
printf("Before ");
displayList(list);
printf("\n");
printf("Added %d", items[i]);
displayList(list);
printf("\n");
i++;
}
}
主要功能:
int main(){
linkedlist *l= (linkedlist *) malloc(sizeof(linkedlist));
CreateList(l, 0);
int a_list[5] = {1, 2, 3, 5, 6};
List(a_list, l, sizeof(a_list)/sizeof(a_list[0]));
printf("A list of five elements: %d", sizeof(a_list)/sizeof(a_list[0]));
displayList(l);
removeLast(l);
addLast(l, 7);
printf("\nAdded something at last position: ");
displayList(l);
printf("\n");
}
我的代碼(我會通過內嵌的意見如何,我認爲我的代碼工作說明)
爲此我得到的輸出:
Before (0)
Added 1(0)
Before (0)
Added 2(0 1)
Before (0 1)
Added 3(0 1 2)
Before (0 1 2)
Added 5(0 1 2 3)
Before (0 1 2 3)
Added 6(0 1 2 3 5)
A list of five elements: 5(0 1 2 3 5)
Added something at last position: (0 1 2 3 5 6)
如您所見,似乎添加的項目只會出現在我對addLast的下一次調用中。
我到目前爲止已經知道它實際上是雖然由於某些原因它不會被打印。如果,例如,我做的是另addLast(list, 6);
電話我剛剛之前關閉功能列表(但外循環,當然!),輸出線Added something at last position...
(其中addLast(l, 7);
呼叫後會發生將實際顯示Added something at last position: (0 1 2 3 5 6 6)
。
所以,我究竟做錯了什麼?
謝謝!
你能否顯示你的'removeLast(l);'函數?它被稱爲,而不是在你的樣本中被取代。 – Bruce
Ooops。我的錯。我在代碼中移除了我_compiled_。然而,正如已經指出的那樣,我的問題似乎是用我的'displayList()',所以它不是那麼相關。感謝您指出這一點:D。 – skytreader