给定 2 个已排序的单链表,合并这些列表。
示例:
list1:1 2 3 5 7
list2:0 4 6 7 10
---> 0 1 2 3 4 5 6 7 7 10
尽管解决方案非常简单,并且有或不使用递归的问题有几种不同的实现(如http://www.geeksforgeeks.org/merge-two-sorted-linked-lists/ 参见方法 3 ),
我想知道这个实现的 O 大复杂性是什么:
- 如果其中一个列表为空,则返回另一个
- 否则,使用 sortedInsert 函数将第二个列表的每个节点插入第一个节点,该函数基本上扫描列表直到找到正确的位置。因为这两个列表都已经排序,所以不需要每次将节点与第一个列表中的所有节点进行比较,我可以从最后添加的节点开始比较。
例如:如果已经添加了 4,则继续前面的示例我可以安全地从 4 开始下一个比较:
list1: 0 1 2 3 4 5 7
list2: 6 7 10
现在比较 6 和 4 而不是 1 2 3 4.. ..
如果我将一个元素与第一个列表中的所有元素进行比较,它将是 O(m*n),其中 m=#list2 和 n=#list1,但考虑到这种“优化”,复杂性是什么?
执行:
// Insert a new node in a sorted list
int sortedInsert(struct ListNode **head, struct ListNode* newNode) {
int headUpdated = 0;
struct ListNode *current;
// The list is empty or the new element has to be added as first element
if (*head == NULL || (*head)->data >= newNode->data) {
newNode->next = *head;
*head = newNode;
headUpdated = 1;
}
else {
// Locate the node before the point of insertion
current = *head;
while (current->next != NULL && current->next->data < newNode->data)
current = current->next;
newNode->next = current->next;
current->next = newNode;
}
return headUpdated;
}
struct ListNode *mergeLists(struct ListNode *head1, struct ListNode *head2) {
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;
// Store the node in the first list where to start the comparisons
struct ListNode *first = head1;
while (head2) {
struct ListNode *head2Next = head2->next;
printf("Adding %d starting comparison from %d\n", head2->data, first->data);
if (sortedInsert(&first, head2))
head1 = first;
first = head2;
head2 = head2Next;
}
return head1;
}