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

    }
  • 相关阅读:
    nginx+keepalived高可用 (主从+双主)
    element ui中table动态列切换时,表格样式变形
    vue中的Swiper使用slideTo提示no function
    element的upload手动submit前动态设置上传请求地址
    使用svg让页面自适应浏览器大小,整体等比缩放
    vue子组件为父组件属性写值
    C#使用SharpZipLib解压多文件的zip压缩文件数据流,保存到本地
    javascript使用正则表达式,从字符串提取内容,多数组解析
    sql server 分组排序
    IE浏览器下错误,不能执行已释放script的代码
  • 原文地址:https://www.cnblogs.com/ttaall/p/14119651.html
Copyright © 2020-2023  润新知