当我将节点插入到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);时,它没有变化;
插入链表的头部将替换其头部,您不能使用函数foo(node * head)来实现。相反,您应该传递head指针的指针,以便函数可以对其进行更改。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句