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

    }
  • 相关阅读:
    页面静态化3 --- 伪静态技术
    9.14[XJOI] NOIP训练33
    9.13[XJOI] NOIP训练32
    Hello world!
    BZOJ-1853: [Scoi2010]幸运数字 (容斥原理)
    luogu1983[NOIP2013pjT4] 车站分级(拓扑排序)
    luogu1113 杂物 (拓扑排序)
    POJ-1094 Sorting It All Out && luogu1347 排序 (拓扑排序)
    BZOJ-1965: [Ahoi2005]SHUFFLE 洗牌 (快速幂+乘转加)
    BZOJ-2705: [SDOI2012]Longge的问题 (欧拉函数)
  • 原文地址:https://www.cnblogs.com/ttaall/p/14119651.html
Copyright © 2011-2022 走看看