2013-05-03 97 views
1

我的代碼編譯正確,但是當我執行時,insertLast被調用兩次,然後我的程序凍結。我看不出爲什麼它會工作兩次,但後來凍結。凍結添加到鏈接列表(C)

到節點發送到我的鏈表代碼:

int main() 
    { 
    LinkedList* canQueue=createList(); 

    for(ii = 0; ii < 10; ii++) 
     { 
     TinCan* tempCan = (TinCan*) malloc(sizeof(TinCan)); 
     insertLast(canQueue, tempCan); 
     } 

    return 0; 
    } 

而且我用鏈表的方法:

LinkedList* createList() /*creates empty linked list*/ 
    { 
     LinkedList* myList; 
     myList = (LinkedList*)malloc(sizeof(LinkedList)); 
     myList->head = NULL; 
     return myList; 
    } 



void insertLast(LinkedList* list, TinCan *newData) 
    { 
    int ii = 1; 
    LinkedListNode* newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode)); 
    newNode->data = newData; 
    newNode->next = NULL; 

     if(list->head == NULL) 
      { 
     list->head = newNode; 
     newNode->next=NULL; 
     } 
    else 
     { 
     LinkedListNode* current = list->head; 
     while (current->next != NULL) 
      { 
      current = current->next; 
      } 
     current->next = newNode; 
     ii++; 

     } 
} 
+2

有些奇怪的是,你不要在main中聲明'ii',而在'insertLast'中有一個本地'ii',它似乎沒有做任何事情。 – 2013-05-03 01:31:13

回答

1

它看起來像你設定的第一個節點是它是自己的鄰居。請注意,您正在使用指針,並且它們不一定複製基礎對象。

list->head = newNode; 
    newNode->next=NULL; 
    current = list->head; 
    current->next = newNode; 

在開始你的頭,然後newnode作爲頭(電流= newnode)的電流進而current.next = newnode(newnode.next = newnode)。因爲你處於一個while循環中,你將永遠循環這個節點直到你退出程序。

+0

謝謝我現在看到了問題 – Dawson 2013-05-03 01:41:10