美文网首页
Leetcode21-Merge Two Sorted List

Leetcode21-Merge Two Sorted List

作者: LdpcII | 来源:发表于2018-03-14 15:36 被阅读0次

21. 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 result(0),让new_head指向这个头结点;然后比较两个链表,将较小的节点插入到new_head后右移该节点的指针和new_head指针,直到两个链表有一个为空指针;连接剩余的非空的链表;最后返回result.next。

My Solution(C/C++完整实现):

#include <stdio.h>
#include <iostream>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    ListNode * Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode result(0);
        ListNode *new_head = &result;
        while (pHead1 && pHead2) {
            if (pHead1->val < pHead2->val) {
                new_head->next = pHead1;
                pHead1 = pHead1->next;
            }
            else {
                new_head->next = pHead2;
                pHead2 = pHead2->next;
            }
            new_head = new_head->next;
        }
        if (pHead1) {
            new_head->next = pHead1;
        }
        if (pHead2) {
            new_head->next = pHead2;
        }
        return result.next;
    }
};

int main() {
    ListNode a(1);
    ListNode b(2);
    ListNode c(4);
    ListNode d(5);
    ListNode e(7);
    ListNode A(3);
    ListNode B(5);
    ListNode C(6);
    ListNode D(8);
    ListNode E(10);
    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &e;
    A.next = &B;
    B.next = &C;
    C.next = &D;
    D.next = &E;
    Solution s;
    ListNode *result = s.Merge(&a, &A);
    while (result) {
        printf("%d->", result->val);
        result = result->next;
    }
    return 0;
}

结果:

1->2->3->4->5->5->6->7->8->10->

My Solution(Python):

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        new_head = ListNode(0)
        result = new_head
        while l1 and l2:
            if l1.val <= l2.val:
                new_head.next = l1
                l1 = l1.next
            else:
                new_head.next = l2
                l2 = l2.next
            new_head = new_head.next
        if l1:
            new_head.next = l1
        if l2:
            new_head.next = l2
        return result.next

相关文章

网友评论

      本文标题:Leetcode21-Merge Two Sorted List

      本文链接:https://www.haomeiwen.com/subject/bvvfqftx.html