How does indirection work in this code?

 ̄綄美尐妖づ 提交于 2019-12-04 06:14:47

问题


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 ?


回答1:


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


来源:https://stackoverflow.com/questions/16924142/how-does-indirection-work-in-this-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!