題目
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.
分析:
合并兩個(gè)已排序的鏈表,由于新鏈表也需要排序软免,所以需要依次判斷鏈表中的各個(gè)數(shù)值大小钓瞭。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode * temp,*temp2,* ans;
temp=NULL;temp2=NULL;ans=NULL;
while(l1!=NULL&&l2!=NULL)
{
temp=(struct ListNode *)malloc(sizeof(struct ListNode));
if(l1->val<l2->val)
{
temp->val=l1->val;
l1=l1->next;
}
else
{
temp->val=l2->val;
l2=l2->next;
}
temp->next=NULL;
if(ans==NULL)
{
ans=temp;
temp2=temp;
}
else
{
temp2->next=temp;
temp2=temp;
}
}
while(l1!=NULL)
{
temp=(struct ListNode *)malloc(sizeof(struct ListNode));
temp->val=l1->val;
l1=l1->next;
temp->next=NULL;
if(ans==NULL)
{
ans=temp;
temp2=temp;
}
else
{
temp2->next=temp;
temp2=temp;
}
}
while(l2!=NULL)
{
temp=(struct ListNode *)malloc(sizeof(struct ListNode));
temp->val=l2->val;
l2=l2->next;
temp->next=NULL;
if(ans==NULL)
{
ans=temp;
temp2=temp;
}
else
{
temp2->next=temp;
temp2=temp;
}
}
return ans;
}
先對(duì)兩個(gè)非空鏈表進(jìn)行比較胧砰,最后不要忘記多余鏈表的數(shù)值。
while(l1!=NULL)
{
temp2->next=l1;
}
最后的合并這樣寫會(huì)更簡(jiǎn)單牢裳。