如何在链表中遍历后得到列表的头

how to get head of the list after traversal in Linked lists?

本文关键字:列表 遍历 链表      更新时间:2023-10-16

我遍历了一个链表,结果在head中达到NULL。在这中间,我修改了head中的一些元素。我该如何在修改后取回指针。

Node* temp=head;
while(head&&head->next){
    head=head->next->next;
}

我希望将链表修改为具有备用节点的新链表。那么,在这之后,我如何才能取回新的指针。

编辑:

ListNode* temp=head,*new1=head;
        while(head!=NULL&&head->next){
            new1->next=head->next->next;
            head->next=head->next->next;
            new1=new1->next;
        }
        //temp=head;
        return new1;

我想你的意思是:

Node* temp = head;
while(temp && temp->next){
    temp = temp->next->next;
}

这样,你总是有头脑的。

一种方法是使用不同的指针遍历列表,而不使用head

另一种方法是在完成后恢复head。您的代码似乎表明这是可能的,因为在进入循环之前,您已经将head存储在temp中。

head = temp;
new1 = temp;