leetcode21:Merge Two Sorted Lists

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Somnus_k/article/details/82590668

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

		ListNode p =l1;
		ListNode q = l2;
		ListNode head = new ListNode(-1);
		ListNode tmp =head;
		while(p!=null&&q!=null){
			if(p.val<=q.val)
				{
				tmp.next=p;
				p=p.next;
				}
			else
				{
				tmp.next=q;
				q=q.next;
				}
			tmp=tmp.next;
		}
		if(p!=null)
			tmp.next=p;
		if(q!=null)
			tmp.next=q;
        //可以将head.next保存下来,然后将head置为null,方便GC
		return head.next;
	}

猜你喜欢

转载自blog.csdn.net/Somnus_k/article/details/82590668