我想通过合并两个给定的列表来创建一个新的链表。新列表包含新节点,这些新节点具有来自list1和list2中的节点的键,从list1的第一个节点的键开始,然后是list2的第一个节点的键,依此类推。
该代码不会停止运行,我认为while循环和交错条件(Node *,Node *)中存在一些逻辑错误
有谁知道如何修理它?先感谢您
struct Node {
int key;
Node* next;
};
Node* copyList(Node*head){
if (head ==NULL){
return NULL;
} else {
Node* newn = new Node;
newn -> key = head->key;
newn->next = copyList(head->next);
return newn;
}
}
Node* interleave(Node* list1, Node* list2){
Node* l1 = copyList(list1);
Node* l2 = copyList(list2);
if (l1==NULL){ //list1 is empty
return l2;
}
else if (l2==NULL){ //list2 is empty
return l1;
}
else { // when both lists are not empty
while (l1->next!=NULL && l2->next!=NULL){
Node* temp = l2;
temp->next = l1->next;
l1->next = temp;
l1=l1->next->next;
l2=l2->next;
}
if (l1->next==NULL){ //when list1 only has a single node
l1->next= l2;
} else if (l2->next ==NULL){ //when list2 only has a single node
l2->next=l1->next;
l1->next =l2;
}
return l1;
}
}