题目:输入两个递增的排序链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
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;
}