Runtime: 5 ms, faster than 100.00% of Java online submissions for Merge Two Sorted Lists.
小周还有这么一天吗!
Solution 1:
不用开辟新的结点,直接改变原两条链表的指针然后merge。
借用l1当做新的头指针,临时用一个头结点t,l1起初指向t。t作为连接用的指针。
最后返回时,返回l1.next就除掉头结点了。
/**
* 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) {
ListNode p=l1;
ListNode q=l2;
ListNode t=new ListNode(-1);
t.next=null;
l1=t;
while(p!=null&&q!=null){
if(p.val<=q.val){
t.next=p;
t=t.next;
p=p.next;
}
else{
t.next=q;
t=t.next;
q=q.next;
}
}
if(q==null){
t.next=p;
}
else{
t.next=q;
}
return l1.next;
}
}