【问题标题】:can't understand sortedlinklist function看不懂 sortedlinklist 函数
【发布时间】:2014-04-13 09:24:31
【问题描述】:

从斯坦福CS图书馆找了一些问题,问题如下

编写一个 SortedInsert() 函数,它给出一个按升序排序的列表,以及一个 单个节点,将节点插入到列表中正确的排序位置。而推() 分配一个新节点以添加到列表中,SortedInsert() 获取一个现有节点,并且只是 重新排列指针以将其插入到列表中。有很多可能的解决方案 问题。

我找到了一个我很难理解的有趣解决方案

void SortedInsert(struct node** headRef, struct node* newNode) {
    struct node **pp, *curr;

    pp = headRef;
    while ((curr = *pp) != NULL && curr->data <= newNode->data)
        pp = &curr->next;
    *pp = newNode;
    newNode->next = curr;
}

有人可以向我解释这是如何工作的吗? 我知道curr设置为*pp(headRef),curr在while循环中设置为*pp,然后检查当前节点是否小于要插入的节点,然后将pp设置为下一个节点当前的一个。 让我绊倒的是,当条件失败并跳转到

*pp = newNode;
newNode -> next = curr;

由于 curr 在 while 循环中被重置为 *pp,newNode 是如何被它后面的那个连接起来的? 还是我完全误读了这个解决方案......

【问题讨论】:

  • 你不需要 curr 指针。恕我直言,for 循环而不是 while 循环将更具可读性。空格也有帮助。
  • 而且你也不需要 pp,因为你可以使用 headRef。

标签: c data-structures linked-list


【解决方案1】:

pp 是指向指针的指针,所以在这一行 pp = &amp;curr-&gt;next; 你分配了 pp 指针地址(不是它自己的下一个元素的地址),它保存下一个元素的地址,所以稍后,在这里*pp = newNode;你'进入'存储下一个元素地址的房间,并将其替换为newNode的地址。

【讨论】:

    【解决方案2】:

    简化版:

    void SortedInsert(struct node **headRef, struct node *newNode) {
    
            for ( ; *headRef && (*headRef)->data <= newNode->data; headRef = &(*headRef)->next)
                {;}
    
               /* When we arrive here, headRef points to the ->next pointer
               ** that points to the node that should come after the newNode
               ** , OR it points to the terminal ->next pointer,
               ** which will be NULL.
               ** In the case of an empty list, *headRef will be NULL, and
               ** the loop is never entered.
               */
            newNode->next = *headRef;
            *headRef = newNode;
    }
    

    【讨论】:

      【解决方案3】:

      你提到:

      “既然 curr 在 while 循环中被重置为 *pp,newNode 是如何被它后面的那个连接起来的?或者我完全误读了这个解决方案......”

      实际上,正如您在代码中看到的那样,“curr”在循环开始时一直分配给(新的、更新的)pp:

      while ((curr = *pp) != NULL && curr->data <= newNode->data)
          pp = &curr->next;
      

      (cur == *pp) 不仅用于启动,而且在每个循环中都执行.. 并且 pp 也不断前进到列表中的下一项 (pp = &curr->next) 直到列表末尾 (*pp == NULL)

      【讨论】:

        猜你喜欢
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-21
        • 2015-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多