1. 程式人生 > >面試題25:合併兩個排序的連結串列

面試題25:合併兩個排序的連結串列

題目:輸入兩個遞增的排序連結串列,合併這兩個連結串列並使新連結串列中的節點仍然是遞增排序的。

c++實現:

 //合併兩個排序的連結串列
   ListNode* merge(ListNode* pHead1, ListNode* pHead2)
   {
   	if(pHead1==NULL)
   		 return pHead2;
   	else if(pHead2==NULL)
	{
	   	return pHead1;
	} 
   	ListNode* root = NULL;
   	ListNode* current = NULL;
   	while(pHead1!=NULL && pHead2!=NULL)
   	{
   		if(pHead1->m_nkey<=pHead2->m_nkey)
		   {
		   	if(root==NULL)
				{
				   	current = pHead1;
				   	root = current; 				
				}
			else{
					current->m_pNext = pHead1;
					current = current->m_pNext;
			    }
				pHead1 = pHead1->m_pNext;		
		   }
		else
		{
			if(root==NULL)
			{
				current = pHead2;
				root = current;		
			}
			else{
				current->m_pNext = pHead2;
				current = current->m_pNext;
			}
			pHead2 = pHead2->m_pNext;
		}   	
	}
	if(pHead1!=NULL)
	current->m_pNext = pHead1;
	if(pHead2!=NULL)
	{
		current->m_pNext = pHead2;
	} 
	return root; 
	   
	} 

JAVA實現:

//合併兩個排序的連結串列
	public static ListNode merge(ListNode head,ListNode head1)
	{
		System.out.println("aaa");
		if(head==null)
		return head1;
		if(head1==null)
			return head;
		
		ListNode root = null;
		ListNode current = null;
		while(head!=null && head1!=null)
		{
			if(head.data<=head1.data)
			{
				if(root == null)
				{
					root = head;
					current = head;
				}
				else {
					current.next = head;
					current = current.next;
					
				}
				head = head.next;
			}
			else {
				if(root == null)
				{
					root = head1;
					 current = head1;
				}
				else {
					current.next = head1;
					current = current.next;
					
				}
				head1 = head1.next;
			}
			
		}
		System.out.println("bbb");
		if(head!=null)
			current.next = head;
		if(head1!=null)
			current.next = head1;
		return root;
	}