簡體   English   中英

鏈表插入函數 - 通過指針傳遞列表

[英]linked list insert function - passing a list by pointer

我試圖創建鏈接列表插入函數,它接受一個列表(或更正確的指向它的指針),然后將值插入列表的末尾。

void ll_insert(struct ll **l, int n){
  struct ll *temp=NULL;
  while ( (*l) != NULL){
    temp= (*l);
    (*l) = (*l)->next;
  }
  (*l)= (struct ll*)malloc(sizeof(struct ll));
  (*l)->n=n;
  (*l)->next=NULL;
  if (temp) temp->next= (*l);
}


int main(void){
  struct ll *l=NULL;                                                                                                                                                         
  ll_insert(&l, 1);
  printf("%d ", l->n);
  ll_insert(&l, 1);
  ll_insert(&l, 2);
  ll_insert(&l, 3);
  printf("%d ", l->n); 

}

運行上面代碼后的輸出是1 3.這並不奇怪,因為

(*l) = (*l)->next;

更新列表以指向結束節點,每次運行insert(...)時,列表的頭部都會更新為指向結束(如果我沒有錯)。 這有什么辦法?

您沒有正確使用指針指針: while循環中的這一行

(*l) = (*l)->next;

應該

l = &((*l)->next);

如果以這種方式使用它,則根本不需要temp變量。

因為這是C而不是C ++,所以不能轉換malloc

如果函數插入空列表,則只應更改* l,因為這是列表的第一個元素發生更改的唯一情況。 這可以通過在函數內部使用局部變量而不是* l來實現(初始化為* l)。

如果你不移動指針l,那么它仍然在列表的頭部。 首先將l分配給temp,然后沿列表移動temp,但只保留指針l。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM