码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] 21 - Merge Two Sorted Lists

时间:2015-01-27 14:56:08      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

原题链接:https://oj.leetcode.com/problems/merge-two-sorted-lists/


这道题用指针的指针实现,做法会非常简单干净。直接上代码

/**
 * 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) {
        ListNode *head = NULL;
        ListNode **pp = &head;
        ListNode *p1 = l1;
        ListNode *p2 = l2;
        
        while (p1 && p2) {
            if (p1->val < p2->val) {
                *pp = p1;
                p1 = p1->next;
            } else {
                *pp = p2;
                p2 = p2->next;
            }
            pp = &(*pp)->next;
        }
        
        while (p1) {
            *pp = p1;
            pp = &(*pp)->next;
            p1 = p1->next;
        }
        
        while (p2) {
            *pp = p2;
            pp = &(*pp)->next;
            p2 = p2->next;
        }
        
        return head;
    }
};


[Leetcode] 21 - Merge Two Sorted Lists

标签:

原文地址:http://blog.csdn.net/algorithmengine/article/details/43194731

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!