leetcode #21 in cpp
2016-05-22 04:24
585 查看
The question is to merge two sorted linked list into one sorted linked list.
Solution:
Solution 1. Use recurrence.
The recurrence structure is as following:
ListNode* merge(ListNode *l1, ListNode *l2){
1. initialize ListNode * head = min(l1->val, l2->val).
2. head->next = merge(new_l1, new_l2) //(new_l1 = l1->next if l1->val < l2 ->val, otherwise new_l1 = l1; new_l2 = l2->next if l2->val < l1->val, otherwise new_l2 = l2.)
3. return head;
}
Code:
Solution 2: Use iterations. Basically it is the same as recurrence, but with loops rather than recurrence call.
Code:
Solution:
Solution 1. Use recurrence.
The recurrence structure is as following:
ListNode* merge(ListNode *l1, ListNode *l2){
1. initialize ListNode * head = min(l1->val, l2->val).
2. head->next = merge(new_l1, new_l2) //(new_l1 = l1->next if l1->val < l2 ->val, otherwise new_l1 = l1; new_l2 = l2->next if l2->val < l1->val, otherwise new_l2 = l2.)
3. return head;
}
Code:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(!l1) return l2; if(!l2) return l1; ListNode *head = new ListNode(l1->val<l2->val?l1->val:l2->val); head->next = mergeTwoLists(l1->val<l2->val?l1->next:l1,l1->val<l2->val?l2:l2->next); return head; } };
Solution 2: Use iterations. Basically it is the same as recurrence, but with loops rather than recurrence call.
Code:
ListNode *l3 = new ListNode(0); ListNode *head = l3; if(l1==NULL) return l2; if(l2==NULL) return l1; while(l1!=NULL && l2 != NULL){ l3->next = new ListNode(0); l3 = l3->next; l3->val = l1->val > l2->val ?l2->val:l1->val; l1->val > l2->val ?l2 = l2->next:l1 = l1->next; } if(l1 == NULL && l2 == NULL) return head->next; l3->next = new ListNode(0); l3->next = l1 == NULL ?l2:l1; return head->next;
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++中const用法总结
- CPP 虚函数、虚函数表及虚拟继承(转)
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- Deploying Control Plane Policing
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解