简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
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.
» Solve this problemDifferent from merge k sorted lists, this problem asks for merge in place. So we can't create a new list to put the merged lists. So here, I opened two pointers which point to two different lists, and compare. The idea is exactly the same as merge sort.
When using the pointers to make change, we need to be very careful that we are changing the right one!
There is another version that using multiset to do this problem which is more concise, while is more expensive.
Multiset is a set whose elements obey the weak ordering rule. Multiset is slower than unordered_multiset. And normally, the unordered_multiset is implemented by binary search tree.
/** * 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||!l2) return l1==NULL? l2 : l1; ListNode *pre = new ListNode(-1); ListNode *cur = pre; while(l1&&l2){ if(l1->val>l2->val){ cur->next = l2; cur = cur->next; l2 = l2->next; } else{ cur->next = l1; //if(!pre->next) pre->next = cur; cur = cur->next; l1 = l1->next; } } if(l1||l2) cur->next = l1==NULL? l2 : l1; ListNode *head = pre->next; delete pre; return head; } };
No comments:
Post a Comment