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;
      }
    };

  • 相关阅读:
    常用的android弹出对话框
    Android 启动后台运行程序(Service)
    java 日期获取时间戳
    stringbuffer与stringbuilder的区别
    Linux记录-sysctl.conf优化方案
    Linux记录-salt分析
    Hadoop记录-fair公平调度队列管理
    Linux记录-GC分析
    Hadoop记录-hdfs转载
    Linux记录-salt-minion安装
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4765850.html
Copyright © 2011-2022 走看看