合并两个有序单链表

题目原型:

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 ListNode mergeTwoLists(ListNode l1, ListNode l2) 
	{
        if(l1==null&&l2==null)
        	return null;
        else if(l1==null)
        	return l2;
        else if(l2==null)
        	return l1;
        else
        {
        	ListNode p,q,head,t;
        	p = l1;
        	q = l2;
        	head = p.val<=q.val?p:q;
        	while(p!=null&&q!=null)
        	{
        		if(p.val<=q.val)
        		{
        			t = p.next;
        			if(t!=null)
        			if(q.val<t.val)
        			{
        				p.next = q;
        				p = t;
        			}
        			else
        			{
        				p = t;
        			}
        			else
        			{
        				p.next = q;
        				break;
        			}
        				
        		}
        		else
        		{
        			t = q.next;
        			if(t!=null)
        			if(p.val<=t.val)
        			{
        				q.next = p;
        				q = t;
        			}
        			else
        			{
        				q = t;
        			}
        			else
        			{
        				q.next = p;
        				break;
        			}
        		}
        	}
        	return head;
        }


 

 

posted on 2014-01-07 15:42  love so much  阅读(159)  评论(0编辑  收藏  举报

导航