gpt4 book ai didi

c - 合并两个链表

转载 作者:行者123 更新时间:2023-11-30 17:02:26 25 4
gpt4 key购买 nike

我在合并 2 个列表时遇到问题,所以我(认为)正在做的是。将列表A分配给当前,转到当前的最后一个节点,将列表B添加到当前,将当前分配给head2,最后打印。但是当我运行它时什么也没有出现,head2 列表仍然为空

#include<stdio.h>
#include<stdlib.h>
typedef struct node {
int val;
struct node * next;
} node_t;

void print_list(node_t * head);
node_t* merge(node_t *head,node_t *head1);

int main(){
int number;
node_t * head = NULL;
node_t * head1 = NULL;

//inputA
//inputB

printf("merged list is : \n");
print_list(merge(head,head1));
printf("\n");
return 0;
}

node_t *merge(node_t *head,node_t *head1){
node_t * current = head;
while(current->next != NULL){
current = current->next;
}
current->next = head1;
return current;
}
void print_list(node_t * head) {
node_t * current = head;

while (current != NULL) {
printf("%d ", current->val);
current = current->next;
}
}

编辑:头是列表 A,头 1 是列表 B,已经有一些数据。它只会保留 A ex 的最后一个节点。 A = 1 2 3 ,B = 4 5 6 返回 3 4 5 6

最佳答案

两个问题:

merge 传递的是 head2 的副本,因此 main 中的 head2 不会改变。您需要传递一个指向 head2 的指针。

void merge(struct node *head,struct node *head1,struct node **head2)
{
//the merge is ok, but the beginning of the list
//is head not head1

// dereference the pointer to head2 to change
// the value of head2 in main.
*head2 = head;
}

此外,这实际上是追加操作而不是合并。

关于c - 合并两个链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36538659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com