簡體   English   中英

鏈表遍歷有什么問題?

[英]what's wrong with this linked list traversal?

我必須解決一個簡單的問題,即已為我提供了鏈表的頭節點,並且必須將指針返回到最后一個節點。

這是兩個實現:

這是行不通的(我嘗試過leetcode和geekforgeeks),它導致SEGMENTATION FAULT:

node* traversal(node* head){
    node* temp=head;
    while(temp!=NULL) temp=temp->next;

    return temp;
}

這個很好用:

node* traversal(node* head){
    node *tail,*temp=head;

    while(temp!=NULL){
        tail=temp;
        temp=temp->next;
    }

    return tail;
}

請告訴我第一個代碼有什么問題,因為根據我的說法,兩個代碼是相同的。...但是第一個代碼始終會給出SEGMENTATION FAULT

第一個代碼塊中的問題是:瞬間循環將中斷temp指向NULL,並且返回相同的指針,即指向最后一個節點的指針。

當循環迭代器(即temp移到最后一個節點的下一個節點)時,需要使用一個引用指針來存儲最后一個節點引用,這意味着temp具有NULL值,然后返回該函數。

為了解決這兩個變量,將需要獲取鏈接列表的最后一個節點:

node *tail; // to assign the reference 
node *next = head; // to iterate through the link list.

第一種情況下要檢查的條件需要修改

node* traversal(node* head){
   node* temp=head;
   //when next node is null, that means this is the last node
   //break out of the while loop when you are at last node
   while(temp->next !=NULL){ 
      temp=temp->next;
   }
   //Return the pointer to the last node
   return temp;
}

根據您的原始代碼,您可能會temp指向null,並且當您嘗試從調用函數中取消引用時,這將返回SEGMENTATION FAULT

暫無
暫無

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

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