题目
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
题解
无官方题解
执行用时 : 2 ms, 在Merge Two Sorted Lists的Java提交中击败了98.56% 的用户
内存消耗 : 35.8 MB, 在Merge Two Sorted Lists的Java提交中击败了87.73% 的用户
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)return l2;
if(l2==null)return l1;
ListNode head;
ListNode temp;
ListNode pos1 = l1;
ListNode pos2 = l2;
ListNode now;
if(pos1.val>pos2.val) {
now=head=l2;
pos2=pos2.next;
}
else if(pos1.val<pos2.val){
now=head=l1;
pos1=pos1.next;
}else{
head=l1;
now=l2;
pos1=pos1.next;
pos2=pos2.next;
head.next=now;
}
while(pos1!=null&&pos2!=null){
if(pos1.val>pos2.val){
temp=pos2;
pos2=pos2.next;
now.next=temp;
now=temp;
}else if(pos2.val>pos1.val){
temp=pos1;
pos1=pos1.next;
now.next=temp;
now=temp;
}else{
temp=pos2;
pos2=pos2.next;
now.next=temp;
now=temp;
temp=pos1;
pos1=pos1.next;
now.next=temp;
now=temp;
}
}
if(pos1!=null){
now.next=pos1;
}
if(pos2!=null){
now.next=pos2;
}
return head;
}
}
这道题居然都弄了8次才过。。。主要还是各种边界条件没搞好。
一开始甚至没注意是合并有序链表生成一个有序列表。。。以为是第一个和第一个相连,第二个和第二个相连,依次类推,提交后才发现会错了意……
感想
链表指针还是要踏踏实实一步一步来呀~