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

合并两个排序的链表

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

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

全部评论

相关推荐

昨天 13:37
门头沟学院 Java
点赞 评论 收藏
分享
字节一直是我的白月光,考虑到转正还是拒了日常实习。
从今天开始狠狠卷JV...:为什么你释放的offer没流到我头上
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务