【问题标题】:Shifting of head pointer of singly soretd linked list while inserting a node插入节点时单排链表头指针的移动
【发布时间】:2015-07-20 19:10:56
【问题描述】:

这是一个以 c++ 风格定义的函数,用于在预排序的链表中插入一个值。函数参数是指向链表头和插入值的指针。请忽略结束条件,列表按非升序排序: 列表15->12->9->6->3 插入元素7 必需的 o/p:15->12->9->7->6->3 但它给了9->7->6->3

请指出我的错误,因为我将双指针传递给第一个节点但没有改变功能。

void llist::Insert_in_sorted_list(node **head_ref, int data) {
    node *head, *ptr;
    head = *head_ref;
    while (head->next->data > data) {
        head = head->next;
    }

    ptr = new node;
    ptr->data = data;
    ptr->next = head->next;
    head->next = ptr;
}

【问题讨论】:

    标签: linked-list parameter-passing


    【解决方案1】:

    您很可能在主程序中使用名称“head”本身作为列表的起点。而在这个函数中,你实际上是在使用“head”并使“head”遍历直到遇到小于输入值的下一个元素。

    所以头部现在是输入值之前的元素。

    要解决此问题,只需在此 Insert_in_sorted_list(node **head_ref,int data) 函数中将节点指针“*head”重命名为“*currentNode”即可。

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2018-04-05
      • 2021-02-25
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 2011-12-14
      • 1970-01-01
      相关资源
      最近更新 更多