题解 | #合并两个排序的链表#

合并两个排序的链表

https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
       	ListNode * l1=pHead1;
        ListNode * l2=pHead2;
		ListNode  h=(ListNode(-1));
		ListNode * head=&h;
		ListNode * cur =head;
		//2 ptr,get the smaller node,and move it to the next,
	
		for(;l1!=nullptr&&l2!=nullptr;){
			
			if(l1->val>l2->val){
				cur->next=l2;
				l2=l2->next;
			}else{
				cur->next=l1;
				l1=l1->next;
			}
			cur=cur->next;
		}

		if(l1==nullptr)
			cur->next=l2;
		else
			cur->next=l1;
		
		l1=head->next;
		//free(head); it is stored in stack

		return l1;
		
    }
};

一开始想着l2拼到l1

其实双指针一个个抽出来会更清晰些

全部评论

相关推荐

吴offer选手:学到了,下次面试也放张纸在电脑上,不然老是忘记要说哪几个点
点赞 评论 收藏
分享
求面试求offer啊啊啊啊:1600一个月?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务