一度に 1 つの要素 (各リンク リストから) がコピーされるように、2 つのリンク リストの内容を 1 つにコピーしようとしています。
したがって、私が持っている場合: list1 = [1,2,3]
、およびlist2 = [4,5,6]
、result = [1,4,2,5,3,6]
. 一方のリストが他方より短い場合、残りのノードは結果リストの最後に追加されます。
わずかなバグで動作する私のコードは次のとおりです。最後に余分なノードが作成されます(これは望ましくありません)。
node *list_copy(node *list1, node *list2)
{
node *mylist = newnode();
node *head = mylist;
while (list1 != NULL || list2 != NULL) {
if (list1 != NULL) {
mylist->data = list1->data;
mylist->next = newnode();
mylist = mylist->next;
list1 = list1->next;
}
if (list2 != NULL) {
mylist->data = list2->data;
mylist->next = newnode();
mylist = mylist->next;
list2 = list2->next;
}
}
return head;
}
最後のノードを作成しないように変更するにはどうすればよいですか?
入力例:
List1 = [1,2,3], List2 = [1,2,3,4,5,6], Result = [1,1,2,2,3,3,4,5,6,0];