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

  • 相关阅读:
    Java 在方法和作用域内的内部类
    java 内部类和向上转型
    java 内部类使用 .this 和 .new
    java innerclasses(内部类)
    Java过滤器与SpringMVC拦截器之间的关系与区别
    Maven异常:Could not find artifact
    soapUI测试webservice(参数为xml格式的处理方式)
    maven仓库加载本地包依赖
    spring data jpa的学习总结
    Java 中常用缓存Cache机制的实现
  • 原文地址:https://www.cnblogs.com/shoemaker/p/4765850.html
Copyright © 2011-2022 走看看