2013-12-18 86 views
0

我正在嘗試編寫單向鏈表的基於C的實現。單鏈表實現問題

#include<stdio.h> 
struct sllist { 
    int data; 
    struct sllist *next; 
}; 
void InsertInLinkedList(struct sllist *head, int data, int position); 

int main() 
{ 
    int x; 
struct sllist *s=NULL; 

InsertInLinkedList(s,5,1); 
x=ListLength(s); 
printf("%d\n",x); 
return 0; 
} 


int ListLength(struct sllist *head) 
{ 
    struct sllist *current = head; 
    int count = 0; 
    while (current != NULL) { 
     count++; 
     current = current->next; 
    } 
    return count; 
} 
void InsertInLinkedList(struct sllist *head, int data, int position) 
{ 
    int k = 1; 
    struct sllist *p, *q, *newNode; 
    newNode = (struct sllist *)malloc(sizeof(struct sllist)); 
    if (!newNode) { 
     printf("Memory Error\n"); 
     return; 
    } 
    newNode->data = data; 
    p = head; 
    if (position == 1) { 
     newNode->next = NULL; 
     head = newNode; 
    } else { 
     while ((p != NULL) && (k < position - 1)) { 
      k++; 
      q = p; 
      p = p->next; 
     } 
     if (p == NULL) { 
      q->next = newNode; 
      newNode->next = NULL; 
     } else { 
      q->next = newNode; 
      newNode->next = p; 
     } 
    } 
} 

我嘗試添加一個節點到列表中,然後驗證長度。但是,我得到的結果是0而不是1。我犯了什麼錯誤?

感謝

+0

只是一個fyi,任何時候你在位置1插入,你將失去整個鏈表。 – Joel

回答

2

此代碼:

if (position == 1) { 
    newNode->next = NULL; 
    head = newNode; 
} 

沒有效果......因爲newNode保持超脫,頭迷路。

在鏈表中插入節點的函數應返回修改後的列表,或接受指向指針的指針。像下面這樣:

void InsertHead(struct sllist **list, struct sllist *new_node) { 
    new_node->next = *list; 
    *list = new_node; 
} 
1

爲了進一步解釋馬努 - fatto的意見,即「頭迷路」 - 當你傳遞一個指針的函數,你只有經過了許多的副本。修改函數內部的數字只會修改函數的本地副本。它對調用函數的指針沒有影響。

+0

感謝您的解釋。我在理解實現時遇到了一些問題。當將一個節點添加到列表的末尾時,它會執行q-> next = newNode;不應該是p-> next = newNode,因爲p是最後一個節點的下一個指針? –

+0

有兩個地方代碼「q-> next = newNode」發生......在第一種情況下,p是NULL,所以你絕對不想做p->任何事情。在第二種情況下,p指向插入節點之後的節點。這是q指向之前的那個。 – Aaron