剑指 Offer 25. 合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/*使用双指针交替进行*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* temp1=l1;
struct ListNode* temp2=l2;
struct ListNode* newlist=NULL; /*用于遍历*/
struct ListNode* head=NULL; /*用于return列表中的值,不然newlist是索引到最后一个的数,无法进行全部数据的返回*/
if(l1==NULL)
return l2;
if(l2==NULL)
return l1;
if(temp1->val<temp2->val){
head=temp1; /*先确认新链表的头结点是两个当中最小的哪个*/
temp1=temp1->next;
}
else{
head=temp2;
temp2=temp2->next;
}
newlist=head;
while(temp1 && temp2){
if(temp1->val<temp2->val){
newlist->next=temp1;
temp1=temp1->next;
}
else{
newlist->next=temp2;
temp2=temp2->next;
}
newlist=newlist->next;
}
if(temp1){
newlist->next=temp1;
}
if(temp1){
newlist->next=temp2;
}
return head;
}
此处的注意点为:
1.在开始的时候要初始化两个空指针,一个用来从前往后进行遍历来返回最终的值,一个用来构建新链表。不然无法返回新链表中的全部数据。
2.要先确定新链表中的头结点。