首页 > 解决方案 > 链表温度自动更改

问题描述

我无法理解为什么temp在声明之后将其值从 9 更改为 1:

last->data = (*head_ref)->data;

我目前的目标是反转包含 1、3、5、7 和 9 的链表的第一个和最后一个节点中的数据。

我得到的结果是 9、3、5、7、9。

如果temp等于 last 等于,即使我在更改 last 后没有设置,更改 lasthead_ref会影响吗?temptemp = last

void reverseNode(struct Node** head_ref)
{
    struct Node *last = *head_ref;
    while(last->next != NULL)
    {
        last = last->next;
    }
    struct Node *temp = last;
    printf("%d ", temp->data);      // temp->data = 9
    last->data = (*head_ref)->data;
    printf("%d ", temp->data);      // temp->data = 1
    (*head_ref)->data = temp->data;
}

谢谢!

标签: cpointerslinked-list

解决方案


void reverse(){
struct node *first=NULL,*second=start,*third=start->next;
if(start==NULL){
    printf("No Element to Reverse\n");
}else{
    while(second!=NULL){
        second->next=first;
        first=second;
        second=third;
        if(third!=NULL){
            third=third->next;
        }
    }

    start=first;
}
display(); }

此代码将反转整个链表而不会丢失数据。


推荐阅读