leetcode笔记:Merge Two Sorted Lists

来源:互联网 发布:python exit code 0 编辑:程序博客网 时间:2024/05/17 22:28

一. 题目描述

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.

二. 题目分析

合并两个有序链表,递归或迭代均可以解决。

三. 示例代码

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        ListNode* res = new ListNode(0);        ListNode* temp = res;        while (l1 || l2) {            ListNode* curr = NULL;            if (l1 == NULL) {                curr = l2;                l2 = l2->next;            }            else if (l2 == NULL) {                curr = l1;                l1 = l1->next;            }            else {                if (l1->val < l2->val) {                    curr = l1;                    l1 = l1->next;                }                else {                    curr = l2;                    l2 = l2->next;                }            }            temp->next = curr;            temp = temp->next;        }        return res->next;    }};

四. 小结

该题需要一些边界条件判断。

1 0