這是一個面試問題,但如果有最好的解決方案,我不會。如何合併兩個排序後的鏈接列表?
問題:編寫一個函數(用C#或C++)合併兩個已排序的鏈接列表。給定的數據結構: 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個列表可能具有相同數據的節點(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;
}
請給一些意見,讓我知道你的聰明和良好的解決方案。謝謝!
可能會更好被問及[代碼審查(http://codereview.stackexchange.com/)? – 2013-02-20 14:48:18
大多數列表合併將返回一個新列表,而不是將它們拼接在一起。 – molbdnilo 2013-02-20 16:25:07