1. 程式人生 > >LeetCode演算法學習(9)

LeetCode演算法學習(9)

題目描述

Merge Two Sorted Lists
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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

題目大意

對兩個排好序的連結串列進行合併。

思路分析

分別遍歷,把較小的結點加入到連結串列中。

關鍵程式碼

    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *p = l1, *q = l2;
        ListNode *lm = new ListNode(-1);
        ListNode *pm = lm;
        while (p != NULL && q != NULL) {
            if (p->val >= q->val) {
                pm-
>next = new ListNode(q->val); pm = pm->next; q = q->next; } else { pm->next = new ListNode(p->val); pm = pm->next; p = p->next; } } while (p != NULL) { pm-
>next = new ListNode(p->val); pm = pm->next; p = p->next; } while (q != NULL) { pm->next = new ListNode(q->val); pm = pm->next; q = q->next; } return lm->next; }

總結

嗯,這次複習了連結串列。