小编典典

这段代码如何间接工作?

algorithm

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

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

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


阅读 239

收藏
2020-07-28

共1个答案

小编典典

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; } 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;
}
2020-07-28