• [LeetCode] 21. Merge Two Sorted Lists


    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.

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    12         ListNode *dummy = new ListNode(0);
    13         ListNode *ret = NULL;
    14         
    15         
    16         ListNode *p1 = l1;
    17         ListNode *p2 = l2;
    18         
    19         ListNode *p = dummy;
    20         
    21         while(p1 && p2){
    22             if (p1->val < p2->val){
    23                 p->next = p1;
    24                 p1 = p1->next;
    25             }else{
    26                 p->next = p2;
    27                 p2 = p2->next;
    28             }
    29             p = p->next;
    30         }
    31         
    32         p1 = (!p1) ? p2 : p1;
    33         
    34         while (p1){
    35             p->next = p1;
    36             // don't forget to move p1 !!
    37             p1 = p1->next;
    38             p = p->next;
    39         }
    40         
    41         ret = dummy->next;
    42         delete dummy;
    43         return ret;
    44     }
    45 };
  • 相关阅读:
    POJ 1363
    HDU 1251(trie树)
    POJ 2081
    NYOJ 3(多边形重心)
    电子琴源码
    POJ 2503
    推荐些在线小制作小工具
    C# 在 webBrowser 光标处插入 html代码 .
    IIS自动安装程序(免费)
    developer express右键菜单显示汉化
  • 原文地址:https://www.cnblogs.com/amadis/p/5926537.html
Copyright © 2020-2023  润新知