【问题标题】:Lost node when insert to head [duplicate]插入头部时丢失节点[重复]
【发布时间】:2016-03-20 15:02:21
【问题描述】:

当我将节点插入 head 时,它不起作用。但插入到其他位置效果很好。

这是我的插入函数

int insert_before(ListNode *head, ListNode *p, int x){ 
ListNode *tmp, *cursor;
if(head == NULL || p == NULL) return -1;                                                                                                         
if(head == p){ 
    tmp = malloc(sizeof(ListNode));
    tmp->val = x;
    // insert node
    tmp->next = p;
    p = tmp;

    printf("insert before: \n");
    printList(head);
    return 0;
}   
cursor = head;
while(cursor->next != p && cursor->next != NULL ) cursor = cursor->next;
tmp = malloc(sizeof(ListNode));
tmp->val = x;
//insert node
tmp->next = p;
cursor->next = tmp;


printf("insert before: \n");
printList(head);
return 0;

}

我的主要功能

int main(){
ListNode *head, *tmp;
int x=0;
int arr[5] = {1,2,4,5,6};
head =  createList(arr, 5);
printList(head);
tmp = get_by_index(head,3);

// insert
//insert_after(head, x);
 insert_before(head, tmp, 100);
// insert_before(head, head, 100);
printf("in main: ");
printList(head);

printf("insert_before return %d \n", x);
return 0;

}

当我运行 insert_before(head, tmp,x) 时,它工作正常 , 当我运行 insert_before(head,head,100); 它没有变化;

【问题讨论】:

  • 正如其名称所暗示的,函数insert_before 应该更新变量head 以指向新创建的列表头。在目前的实现中,这是不可能的,因为您是按值传递此变量。

标签: c data-structures


【解决方案1】:

插入到链表的头部替换它的头部,你不能用函数 foo(node *head) 来做。相反,您应该传递头指针的指针,以便函数可以更改它。

【讨论】:

  • 谢谢,我想我的问题与this one重复了
【解决方案2】:

您必须稍微更改代码的语法,

int insert_before(ListNode **head, ListNode *p, int x)

我想你明白我在这里想说的了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多