leetcode解题报告21. Merge Two Sorted Lists

来源:互联网 发布:雷电软件儿 编辑:程序博客网 时间:2024/05/27 20:51

leetcode解题报告21. Merge Two Sorted Lists

题目地址

难度是easy

题目描述

合并两条有序的链表

我的思路

题目比较简单,是一条数据结构方面的题目,难点是链表的操作。
此外,这个题目有一点问题,就是没有显式的说明这个排序是升序还是降序。这样更合理的方式应该通过传入的链表进行检验才行。但是这就比较麻烦了,我还是按照升序来写代码而已。

我的代码

/** * 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 *head, *tail;        if (l1 == NULL)            return l2;        if (l2 == NULL)            return l1;        if (l1->val < l2->val) {            head = l1;            tail = l1;            l1 = l1->next;        } else {            head = l2;            tail = l2;            l2 = l2->next;        }        while (l1 != NULL && l2 != NULL) {            if (l1->val < l2->val) {                tail->next = l1;                tail = tail->next;                l1 = l1->next;            } else {                tail->next = l2;                tail = tail->next;                l2 = l2->next;            }        }        if (l1 != NULL) {            tail->next = l1;        }        if (l2 != NULL) {            tail->next = l2;        }        return head;    }};

阅读官方题解

没有官方题解。

思想核心总结

考察链表操作,对链表操作,画图是一个很好的技巧。