简体   繁体   English

链表遍历有什么问题?

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

I have to solve a simple problem where i have been provided with the head node of a linked list and i have to return the pointer to the last node. 我必须解决一个简单的问题,即已为我提供了链表的头节点,并且必须将指针返回到最后一个节点。

Here are two implementations: 这是两个实现:

This one doesn't work(I tried leetcode and geekforgeeks) and it causes a SEGMENTATION FAULT: 这是行不通的(我尝试过leetcode和geekforgeeks),它导致SEGMENTATION FAULT:

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

    return temp;
}

This one works just fine: 这个很好用:

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

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

    return tail;
}

kindly tell me what's the fault in the first code because according to me both the codes are identical....however the 1st always gives SEGMENTATION FAULT 请告诉我第一个代码有什么问题,因为根据我的说法,两个代码是相同的。...但是第一个代码始终会给出SEGMENTATION FAULT

The issue in the first code chunk is : The moment loop will break temp is pointing to NULL and the same pointer is getting returned ie pointer to the last node. 第一个代码块中的问题是:瞬间循环将中断temp指向NULL,并且返回相同的指针,即指向最后一个节点的指针。

There needs to take one reference pointer which store the last node reference when the loop iterator ie temp move to the next of the last node meaning temp is having NULL value then the function is getting returned. 当循环迭代器(即temp移到最后一个节点的下一个节点)时,需要使用一个引用指针来存储最后一个节点引用,这意味着temp具有NULL值,然后返回该函数。

In order to resolve this two variable will be required in order to get the last node of the link list: 为了解决这两个变量,将需要获取链接列表的最后一个节点:

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

The condition being checked in the first case needs modification 第一种情况下要检查的条件需要修改

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;
}

As per your original code, you would have temp pointing to null and this when you try to dereference from the calling function will return SEGMENTATION FAULT . 根据您的原始代码,您可能会temp指向null,并且当您尝试从调用函数中取消引用时,这将返回SEGMENTATION FAULT

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM