zoukankan      html  css  js  c++  java
  • [LeetCode] 21

    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.

    /**
    * 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 one is empty, then return another */
        if(l1 == NULL) {
          return l2;
        }
        if(l2 == NULL) {
          return l1;
        }

        ListNode *t1 = l1;
        ListNode *t2 = l2;
        ListNode *tr, *result;
        tr = NULL;
        result = NULL;

        while (t1 || t2) {
          if (t1 == NULL) {
            tr->next = t2;
            break;
          }
          if (t2 == NULL) {
            tr->next = t1;
            break;
          }
          ListNode *tt;
          if (t1->val < t2->val) {
            tt = t1;
            t1 = t1->next;
          } else {
            tt = t2;
            t2 = t2->next;
          }
          if (!result) { // the fisrst time to add a nodel
            tr = tt;
            result = tt;
          } else {
            tr->next = tt;
            tr = tt;
          }
        }
        return result;
      }
    };

  • 相关阅读:
    VS批处理命令使用
    python实现域账号登陆
    Sql Server 优化技巧
    Windows 2012 R2 安装net4.6.1
    Resharper报“Possible multiple enumeration of IEnumerable”
    京东模拟点击
    使用常规方法爬取猫眼电影
    关于断点调试
    看网络开发实战书笔记
    scrapy的request的meta参数是什么意思?
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4765850.html
Copyright © 2011-2022 走看看