2013-07-10 102 views
0

我正在使用鏈接列表並嘗試在where'th節點後面插入一個帶有數據d的新節點。出於某種原因,我得到不正確的結果。這裏是我的代碼:在第n個元素後面插入鏈接列表

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; 
    struct list * new; 

    while(marker -> data != where) 
     marker = marker -> next; 
    new = (struct list*)malloc(sizeof(struct list)); 

    new -> next = marker -> next; 
    marker -> next = new; 
    new -> data = d; 
} 
+0

'marker - > data!=其中'不代表第n個 – BLUEPIXY

回答

0

也許你可以做修改代碼類似這樣(的第一個節點是第0個節點,第二個節點是1號在我的這段代碼):

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; 
    struct list * new; 
    int count = 0; 

    while(count < where) 
    { 
     count++; 
     marker = marker -> next; 
    } 
    new = (struct list*)malloc(sizeof(struct list)); 

    new -> next = marker -> next; 
    marker -> next = new; 
    new -> data = d; 
} 
1

我可以建議一些評論以及更安全的版本:

void insertAfter(int d, int where) 
{ 
    struct list * marker = head; /* it's a little odd that you have named your node struct list */ 
    struct list * new; 

    while(marker && marker->data != where) /* we don't want to end up dereferencing a null pointer */ 
     marker = marker->next; 

    if (!marker) /* we've reached the end of the list and no element was found */ 
    { 
     printf("Element with data %d not found\n", where); /* print some diagnostics */ 
     return; /* let's exit here, no reason to hang about */ 
    } 

    /* if we are here then we've found our element */ 

    struct list * next_node = marker->next; /* let's save the next node */ 

    new = malloc(sizeof(struct list)); /* it is bad practice to cast the result of malloc */ 
    new->data = d; 

    marker->next = new; /* marker now points to the new node */ 

    new->next = next_node; /* the new node now points to the one marker originally pointed to */ 
} 

關於malloc鑄有一個關於它here讀。

0

你的代碼是在節點的數據== where,而不是where'th節點之後插入新節點。你可以寫這樣的:

int i; 
for(i=1; i<where; i++) 
    marker = marker->next; 

此外,最好檢查達到NULL,或者當程序試圖讀取marker->nextmarker->data,會有中止。

相關問題