【问题标题】:Linked list temp changes automatically链表温度自动更改
【发布时间】:2019-02-27 00:22:07
【问题描述】:

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

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

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

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

如果temp 等于last 等于head_ref,即使我在更改last 后没有设置temp = last,更改last 是否会影响temp

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

谢谢!

【问题讨论】:

  • 在此语句中struct Node *temp = last; 的指针与last 相同,并且您正在更改last 的数据,因此temp 反映了该更改。这就是你所看到的。
  • @Azeem 感谢您的澄清!

标签: c pointers linked-list


【解决方案1】:
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(); }

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

【讨论】:

  • 建议必须附有理由。仅代码答案不会。
猜你喜欢
  • 1970-01-01
  • 2015-12-25
  • 2021-02-08
  • 1970-01-01
  • 1970-01-01
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 2016-09-11
相关资源
最近更新 更多