如何间接从事本code? [英] How does indirection work in this code?

查看:114
本文介绍了如何间接从事本code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读答案合并两个有序链表 。 在code:

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是一个指向节点的指针,其目的是保持接下来字段的地址最后一个节点的

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

所以第一行设置指针到下一个节点(无论是列表或previous 于节点>接下来

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

第二行设置pnext到下一步字段中当前节点的

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

在刚刚处理用刚分配pnext了微优化是避免再次提领的List1它的头三线推进的List1

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

这篇关于如何间接从事本code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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