标签:
原题链接: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