如何在链接列表中遍历后获取列表的头部?

时间:2016-05-09 19:43:50

标签: c++ c linked-list singly-linked-list

我遍历了一个链表并最终在头之间达到NULL我修改了一些元素。如何通过这些修改取回头指针。

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;

2 个答案:

答案 0 :(得分:2)

一种方法是使用不同的指针遍历列表,并单独留下head

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

head = temp;
new1 = temp;

答案 1 :(得分:2)

我认为你的意思是:

"Red".tag = 1

那样,你总是有头脑。