leetcode 021 —— Merge Two Sorted Lists

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.


思路:类似归并排序,双指针扫描链表,值小的,就往新链表后面放,最后补齐多余的链表

class Solution {
public:
	ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
		ListNode pre(0);
		ListNode *p = ⪯
		while (l1&&l2){ //有一个为0 就出局
			if (l1->val > l2->val){
				p->next = l2;
				p = l2;
				l2 = l2->next;
			}
			else{
				p->next = l1;
				p = l1;
				l1 = l1->next;
			}
		}
		if (l1) p->next = l1;
		if (l2) p->next = l2;
		return (&pre)->next;
	}
};


阅读更多
上一篇leetcode 020 —— Valid Parentheses
下一篇leetcode 022 —— Generate Parentheses
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭