Loading

21. 合并两个有序链表

题目

 

代码

/**
 * 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* root = nullptr, *ptr = nullptr;
        //小的先加入链表
		while (l1 != nullptr&&l2 != nullptr)
		{
			if (l1->val > l2->val)
			{
				if (root == nullptr)
				{
					root = l2;
					ptr = root;
				}
				else {
					root->next = l2;
					root = root->next;

				}
				l2 = l2->next;


			}
			else
			{
				if (root == nullptr)
				{
					root = l1;
					ptr = root;
				}
				else {
					root->next = l1;
					root = root->next;

				}
				l1 = l1->next;
			}

		}
        //如果l1还有元素存在
		while (l1 != nullptr)
		{
			if (root == nullptr)
			{
				root = l1;
				ptr = root;
			}
			else
			{
				root->next = l1;
				root = root->next;
			}

			l1 = l1->next;
		}
        //如果l2还有元素存在
		while (l2 != nullptr)
		{
			if (root == nullptr)
			{
				root = l2;
				ptr = root;
			}
			else
			{
				root->next = l2;
				root = root->next;
			}

			l2 = l2->next;
		}
		return ptr;

	}
};

 

思路

先同时遍历两个链表,小的先加入新链表中,最后判断l1或者l2是否还有剩余元素,有的话全部再加入新链表。方法时间复杂度O(m+n),空间复杂度O(1)

posted @ 2018-09-15 08:01  李正浩  阅读(83)  评论(0编辑  收藏  举报