Merge Two Sorted Lists-满满的套路

leetcode-21

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists

不带头结点的版本

实现

/**
 1. Definition for singly-linked list.
 2. struct ListNode {
 3.     int val;
 4.     ListNode *next;
 5.     ListNode(int x) : val(x), next(NULL) {}
 6. };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *head = NULL;
        ListNode *tmp = NULL, *cur = NULL;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                tmp = l1;
                l1 = l1->next;
            } else {
                tmp = l2;
                l2 = l2->next;
            }
            if (!head) { 
                cur = tmp;
                head = cur;
            } else {
                cur->next = tmp;
                cur = cur->next;
            }
        }
        if (l1) {
            if (!head)
                head = l1;
            else 
                cur->next = l1;
        }
        if (l2) {
            if (!head)
                head = l2;
            else
                cur->next = l2;
        }

        return head;
    }
};

分析

  1. 两个链表合并,合并后的新链表的头结点不定,这里定义 head 指针指向合并后新链表的头结点。
  2. 使用cur指针指向合并后新链表的当前节点。
  3. 新链表的头结点不定,合并时必须考虑如何确定新链表的头指针。
  4. 因此,上述代码比较复杂,容易出错,而且并不适合应试。

带头结点的版本

代码

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        // 创建一个头结点
        ListNode *head = new ListNode(0);
        ListNode *cur = head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
            } else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }

        cur->next = l1 ? l1 : l2;
        return head->next;
    }
};

分析

  1. 给合并的新链表创建一个头结点,这个头结点作用就是避免合并后新链表头指针无法确定指向哪个节点的问题
  2. 新链表使用cur指针指向头结点
  3. cur->next指针指向每次加入到新链表的节点
  4. 更新新链表的cur指针 cur = cur->next
  5. 跳出while循环后,判断哪一个链表遍历不为空,更新cur->next值为不为空的链表
  6. 返回head->next即为合并后新链表

优点

不带头结点和带头结点版本对比:

1 新链表头头指针带来的问题:
在合并两个排序链表的问题中,新链表创建必须确定新链表的头结点
新链表头指针指向哪个链表中第一个插入到新链表节点由比较结果确定。

2 带头结点的新链表避免头指针不确定的问题:
带头结点的新链表中,只需要把比较中胜出的节点插入到新链表的尾部,即普通的链表尾部插入问题。

通过以上分析,在遇到新链表头指针不确定问题时可以使用创建头结点的方式简化创建新链表的过程,满满的套路。

参考

Merge Two Sorted Lists

To merge k sorted linked lists, one approach is to repeatedly merge two of the linked lists until all k lists have been merged into one. We can use a priority queue to keep track of the minimum element across all k linked lists at any given time. Here's the code to implement this idea: ``` struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; // Custom comparator for the priority queue struct CompareNode { bool operator()(const ListNode* node1, const ListNode* node2) const { return node1->val > node2->val; } }; ListNode* mergeKLists(vector<ListNode*>& lists) { priority_queue<ListNode*, vector<ListNode*>, CompareNode> pq; for (ListNode* list : lists) { if (list) { pq.push(list); } } ListNode* dummy = new ListNode(-1); ListNode* curr = dummy; while (!pq.empty()) { ListNode* node = pq.top(); pq.pop(); curr->next = node; curr = curr->next; if (node->next) { pq.push(node->next); } } return dummy->next; } ``` We start by initializing a priority queue with all the head nodes of the k linked lists. We use a custom comparator that compares the values of two nodes and returns true if the first node's value is less than the second node's value. We then create a dummy node to serve as the head of the merged linked list, and a current node to keep track of the last node in the merged linked list. We repeatedly pop the minimum node from the priority queue and append it to the merged linked list. If the popped node has a next node, we push it onto the priority queue. Once the priority queue is empty, we return the head of the merged linked list. Note that this implementation has a time complexity of O(n log k), where n is the total number of nodes across all k linked lists, and a space complexity of O(k).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值