C 合并两个链表
我在合并2个列表时遇到问题,所以我(认为)正在做的是。将列表A分配给当前,转到当前的最后一个节点,将列表B添加到当前,将当前分配给head2,最后打印。但是当我运行它时,没有任何结果,head2列表仍然为空C 合并两个链表,c,data-structures,linked-list,C,Data Structures,Linked List,我在合并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); nod
#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;
}
}
#包括
#包括
类型定义结构节点{
int-val;
结构节点*下一步;
}节点t;
作废打印列表(节点*头);
节点合并(节点头,节点头1);
int main(){
整数;
节点头=空;
node_t*head1=NULL;
//输入
//输入
printf(“合并列表为:\n”);
打印列表(合并(头,头1));
printf(“\n”);
返回0;
}
节点合并(节点头,节点头1){
节点_t*电流=头部;
while(当前->下一步!=NULL){
当前=当前->下一步;
}
当前->下一步=head1;
回流;
}
无效打印列表(节点头){
节点_t*电流=头部;
while(当前!=NULL){
printf(“%d”,当前->值);
当前=当前->下一步;
}
}
编辑:标题为列表A,标题1为列表B,已经有一些数据。它将只保留A的最后一个节点。例如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;
}
此外,这实际上是一个追加操作,而不是合并。我看到了合并的问题:
*如果左磁头为空,则会出现故障。
*它返回了合并点,而不是真正的新公共头
node_t *merge(node_t *head,node_t *head1){
if (head == NULL)
return head1;
node_t * current = head;
while(current->next != NULL){
current = current->next;
}
current->next = head1;
return head;
}
我建议
head2=merge(head,head1)代码>。。在merge
:返回头代码>我的方法错误,如何保留这两个列表?创建结果的新列表(每个元素)。是的,我错了,这不是合并。怎么做?