[LeetCode]21. Merge Two Sorted Lists

来源:互联网 发布:cas java 编辑:程序博客网 时间:2024/06/05 23:41

[LeetCode]21. Merge Two Sorted Lists

题目描述

这里写图片描述

思路

比较大小合并链表即可,详见代码

代码

#include <iostream>#include <vector>using namespace std;struct ListNode {    int val;    ListNode* next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    void printList(ListNode* head) {        while (head) {            cout << head->val << " ";            head = head->next;        }        cout << endl;    }    ListNode* vector2list(vector<int> nums) {        if (nums.size() == 0)            return NULL;        ListNode* head = new ListNode(nums[0]), *iter = head;        for (int i = 1; i < nums.size(); ++i) {            ListNode* temp = new ListNode(nums[i]);            iter->next = temp;            iter = iter->next;        }        return head;    }    ListNode* mergeTwoList(ListNode* l1, ListNode* l2) {        ListNode* head = new ListNode(0);        ListNode* cur = head;        while (l1 && l2) {            if (l1->val <= l2->val) {                cur->next = l1;                cur = cur->next;                l1 = l1->next;            }            else {                cur->next = l2;                cur = cur->next;                l2 = l2->next;            }        }        if (l1)            cur->next = l1;        else if (l2)            cur->next = l2;        cur = head;        head = head->next;        delete(cur);        cur = NULL;        return head;    }};int main() {    vector<int> nums1 = { 1, 5, 6 }, nums2 = { 2, 3, 4 };    Solution s;    ListNode *l1 = s.vector2list(nums1), *l2 = s.vector2list(nums2);    s.printList(s.mergeTwoList(l1, l2));    system("pause");    return 0;}
0 0
原创粉丝点击