您的位置:首页 > 其它

LeetCode Merge Two Sorted Lists

2014-04-22 13:04 351 查看
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.

public  Node mergeTwoLists(Node l1, Node l2) {
Node p1 = l1;
Node p2 = l2;
Node fakeNode = new Node(0);
Node p = fakeNode;
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
p.next = p1;
p= p.next;
p1= p1.next;
}else{
p.next = p2;
p= p.next;
p2= p2.next;
}
}
if(p2==null){
p.next = p1;
}
if(p1==null){
p.next = p2;
}
return fakeNode.next;
}


p1和p2负责遍历两个链表,指向了两个链表的最小值,通过不断比较将适合的节点放入一个空链表中,并不断移动p1,p2,

当有任何链表遍历结束时,直接将另一条链表的剩余部分接上即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: