【LeetCode】LeetCode——第21题:Merge Two Sorted Lists

21. Merge Two Sorted Lists

    My Submissions
Question Editorial Solution
Total Accepted: 125307  Total Submissions: 353211  Difficulty: Easy

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) {
		if (!l1){return l2;}
		if (!l2){return l1;}
		ListNode* p, * q, *s, *r;
		(l1->val > l2->val) ? (p = l2,q = l1) : (p = l1, q = l2);//p小	q大	p不动
		s = p;
		while(p->next && q){
			(q->val >= p->next->val) ? (p = p->next) : (r = q->next, q->next = p->next, p->next = q, q = r, p = p->next);
		}
		if (!p->next){p->next = q;}
		return s;
    }
};
提交代码,顺利AC掉,Runtime:8ms

你可能感兴趣的:(LeetCode,merge,sorted,LIS,Two)