这段代码中的间接性如何工作? [英] How does indirection work in this code?

查看:16
本文介绍了这段代码中的间接性如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读合并两个排序链表的答案.代码:

#define SWAP_PTRS(a, b) do { void *t = (a);(a) = (b);(b) = t;} 而 (0)节点*合并列表(节点*列表1,节点*列表2){节点 *list = NULL, **pnext = &list;如果(列表2 == NULL)返回列表1;while (list1 != NULL){如果(列表1->数据>列表2->数据)SWAP_PTRS(列表1,列表2);//下面这段代码有什么作用?*pnext = 列表 1;//??pnext = &list1->next;//??list1 = *pnext;//??}*pnext = list2;退货清单;}

我无法理解双指针在这里是如何工作的,值是如何改变的?

解决方案

pnext 是一个指向 Node 的指针的指针,用于保存最后一个节点的 next 字段的地址

所以第一行将指针设置为下一个节点(列表或前一个node->next)

第二行设置pnext到当前节点的next字段

第三行在使用刚刚分配的 pnext 处理它的头部后推进 list1 进行微优化,避免再次取消引用 list1

也可以按照node->next来写:

#define SWAP_PTRS(a, b) do { void *t = (a);(a) = (b);(b) = t;} 而 (0)节点*合并列表(节点*列表1,节点*列表2){节点 *list = NULL, *node ;如果(列表2 == NULL)返回列表1;如果(列表1->数据>列表2->数据)SWAP_PTRS(列表1,列表2);节点=列表=列表1;list1=list1->next;while (list1 != NULL){如果(列表1->数据>列表2->数据)SWAP_PTRS(列表1,列表2);节点->下一个=列表1;节点 = list1->next;list1 = list1->next;}节点->下一个=列表2;退货清单;}

I was reading the answer to Merging two sorted linked list. The code:

#define SWAP_PTRS(a, b) do { void *t = (a); (a) = (b); (b) = t; } while (0)

Node* MergeLists(Node* list1, Node* list2) 
{
  Node *list = NULL, **pnext = &list;

  if (list2 == NULL)
    return list1;

  while (list1 != NULL)
  {
    if (list1->data > list2->data)
      SWAP_PTRS(list1, list2);

   // What does the following piece of code do ?
    *pnext = list1;  // ??
    pnext = &list1->next; // ??
    list1 = *pnext;     // ?? 
  }

  *pnext = list2;
  return list;
}

I am not able to understand how the double pointer is working here, how the values are changed ?

解决方案

pnext is a pointer to a pointer of Node and is meant to hold the address of the next field of the last node

so the first line sets the pointer to the next node (either list or the previous node->next)

the second line sets pnext to the next field of the current node

the third line advances list1 after just dealing with the head of it using the just assigned pnext for a micro-optimization that avoids dereferencing list1 again

you can also write it in terms of node->next:

#define SWAP_PTRS(a, b) do { void *t = (a); (a) = (b); (b) = t; } while (0)

Node* MergeLists(Node* list1, Node* list2) 
{
  Node *list = NULL, *node ;

  if (list2 == NULL)
    return list1;

  if (list1->data > list2->data)
    SWAP_PTRS(list1, list2);

  node=list=list1;

  list1=list1->next;

  while (list1 != NULL)
  {
    if (list1->data > list2->data)
      SWAP_PTRS(list1, list2);

    node->next = list1;  

    node = list1->next; 
    list1 = list1->next;     
  }

  node->next = list2;
  return list;
}

这篇关于这段代码中的间接性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆