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

    }
  • 相关阅读:
    Boliuraque OI 总结
    HNU 1447 最长上升路径
    妹纸
    某个子串的循环节
    跳石头
    小澳的葫芦
    递推式的循环问题
    BZOJ 2326 数学作业
    BZOJ 2337 XOR和路径
    hdu5468 Puzzled Elena
  • 原文地址:https://www.cnblogs.com/ttaall/p/14119651.html
Copyright © 2020-2023  润新知