これはインタビューの質問ですが、最善の解決策があるかどうかはわかりません.
質問: (C# または C++ で) 関数を作成して、既に並べ替えられた 2 つのリンクされたリストをマージします。与えられたデータ構造: C++:
class Node
{
public:
int data;
Node* next;
};
C#:
class Node
{
public int data;
public Node next;
};
関数を実装します: C++ の場合:
Node* Merge (Node* head1, Node* head2)
{
…
}
C# の場合:
Node Merge (Node head1, Node head2)
{
…
}
すでにソートされている 2 つのリンク リスト (昇順) を取り込み、それらを (昇順で) 1 つのソート済みリンク リストにマージし、新しいヘッドを返します。2 つのリストには、同一のデータ (int 値) を持つノードが含まれる場合があります。結果リストに同一のデータがないことを期待しています。
私の解決策:
Node Merge(Node head1, Node head2)
{
Node merged = head1;
// Both lists are empty
if (head1 == null && head2 == null)
{
return null;
}
// List 1 is empty
else if (head1 == null && head2 != null)
{
return head2;
}
// List 2 is empty
else if (head2 == null && head1 != null)
{
return head1;
}
// Both lists are not empty
else
{
Node cursor1 = head1;
Node cursor2 = head2;
if (cursor1.next.data > cursor2.data)
{
Node temp = cursor1;
cursor1 = cursor2;
cursor2 = temp;
}
// Add all elements from list 2 to list 1
while (cursor1.next != null && cursor2 != null)
{
if (cursor1.next.data < cursor2.data)
{
cursor1 = cursor1.next;
}
else
{
Node temp1 = cursor1.next;
Node temp2 = cursor2.next;
cursor1.next = cursor2;
cursor2.next = temp1;
cursor1 = cursor1.next;
cursor2 = temp2;
}
}
if (cursor1.next == null)
{
cursor1.next = cursor2;
}
}
// Remove duplicates
head1 = merged;
while (head1.next != null)
{
if (head1.data < head1.next.data)
{
head1 = head1.next;
}
else if (head1.data == head1.next.data)
{
head1.next = head1.next.next;
}
}
return merged;
}
いくつかコメントをして、あなたの賢くて良い解決策を教えてください。ありがとうございました!