zoukankan      html  css  js  c++  java
  • [面试真题] LeetCode: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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         ListNode *head = new ListNode(0);
    15         ListNode *tail = head;
    16         ListNode *a = l1;
    17         ListNode *b = l2;
    18         while(a || b){
    19             if(a && b && a->val < b->val){
    20                 tail->next = a;
    21                 a = a->next;
    22             }else if (a && b && a->val > b->val){
    23                 tail->next = b;
    24                 b = b->next;
    25             }else if(a){
    26                 tail->next = a;
    27                 a = a->next;
    28             }else{
    29                 tail->next = b;
    30                 b = b->next;
    31             }
    32             tail = tail->next;
    33         }
    34         return head->next;
    35     }
    36 };

    Run Status: Accepted!
    Program Runtime: 56 milli secs

    Progress: 208/208 test cases passed.
  • 相关阅读:
    day02-xml
    day01-java重点复习
    RPM包和YUM仓库管理
    Nginx的下载与安装
    yum源本地部署完后网络部署报错
    RAID和LVM
    磁盘管理
    xargs详解
    locate及find查找命令
    linux的进程和管道符(二)
  • 原文地址:https://www.cnblogs.com/infinityu/p/3074563.html
Copyright © 2011-2022 走看看