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.
Example:
Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
思路One
1.如果两个链表其中有一个为空,就不用判断条件了,直接返回不为空的即可
2.比较两个链表第一个位置的结点值,小的放在temp指针中,不断更新temp指针;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *temp;
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val <= l2->val){
temp = l1;
temp->next = mergeTwoLists(l1->next, l2);
}
if(l1->val > l2->val){
temp = l2;
temp->next = mergeTwoLists(l1, l2->next);
}
return temp;
}
思路Two
就是递归思想的优化啦!!!
把temp结点去掉,优化一下,让两个链表的指针来回指
指来指去啦!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val <= l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}