Sunday, June 9, 2013

Merge 2 sorted lists@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历: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 problem

Different 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

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...