zoukankan      html  css  js  c++  java
  • Leecode no.21 合并两个有序链表

    package com.example.demo.leecode;

    /**
    * 合并两个有序链表
    * @Date 2020/12/11
    * @author Tang
    *
    * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
    *
    * /**
    * * Definition for singly-linked list.
    * * public class ListNode {
    * * int val;
    * * ListNode next;
    * * ListNode() {}
    * * ListNode(int val) { this.val = val; }
    * * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    * * }
    *
    */
    public class MergeTwoSortedLists {

    public ListNode execute(ListNode l1, ListNode l2){

    if(l1 == null){
    return l2;
    }
    if(l2 == null){
    return l1;
    }

    ListNode firstNode;

    ListNode endNode;

    //先确定头节点
    if(l1.val <= l2.val){
    firstNode = l1;
    endNode = firstNode;
    l1 = l1.next;
    }else{
    firstNode = l2;
    endNode = firstNode;
    l2 = l2.next;
    }

    while(true){
    if(l1 == null || l2 == null){
    break;
    }
    if(l1.val <= l2.val){
    endNode.next = l1;
    endNode = l1;
    l1 = l1.next;
    }else{
    endNode.next = l2;
    endNode = l2;
    l2 = l2.next;
    }
    }

    while(l1 != null){
    endNode.next = l1;
    endNode = l1;
    l1 = l1.next;
    }
    while(l2 != null){
    endNode.next = l2;
    endNode = l2;
    l2 = l2.next;
    }
    return firstNode;


    }

    public static void main(String[] args) {

    ListNode left1 = new ListNode(1);
    ListNode left2 = new ListNode(2);
    ListNode left3 = new ListNode(5);
    ListNode left4 = new ListNode(6);
    ListNode left5 = new ListNode(6);
    ListNode left6 = new ListNode(8);
    left1.next = left2;
    left2.next = left3;
    left3.next = left4;
    left4.next = left5;
    left5.next = left6;

    ListNode right1 = new ListNode(1);
    ListNode right2 = new ListNode(2);
    ListNode right3 = new ListNode(2);
    ListNode right4 = new ListNode(7);
    right1.next = right2;
    right2.next = right3;
    right3.next = right4;


    ListNode result = new MergeTwoSortedLists().execute(left1, right1);
    System.out.println(result.val);
    while(result.hasNext()){
    result = result.next;
    System.out.println(result.val);
    }

    }


    }

    class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) {
    this.val = val;
    }
    ListNode(int val, ListNode next) {
    this.val = val;
    this.next = next;
    }
    boolean hasNext(){
    return next != null;
    }

    }
  • 相关阅读:
    使用ATL开发ActiveX控件
    [Silverlight]AutoCompleteBox控件的一个Bug?
    [Silverlight]一个简单的GroupBox控件
    WCF安全之ASP.NET兼容模式
    Mysql 性能优化记录
    【Python+Django+Pytest】数据库异常pymysql.err.InterfaceError: (0, '') 解决方案
    Django在使用logging日志模块时报错无法操作文件 logging error Permission Error [WinError 32]
    isinstance 判断一个对象属于或不属于多种数据类型
    CentOS 系统 查看 cpu核数
    我踩过的python的坑
  • 原文地址:https://www.cnblogs.com/ttaall/p/14119651.html
Copyright © 2011-2022 走看看