博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
合并两个有序单链表
阅读量:4091 次
发布时间:2019-05-25

本文共 2253 字,大约阅读时间需要 7 分钟。

 

一、问题描述

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

 

二、代码实现

/*public class ListNode {    int val;    ListNode next = null;    ListNode(int val) {        this.val = val;    }}*/public class Solution {        public ListNode Merge(ListNode list1,ListNode list2) {        if (list1 == null) {            return list2;        }        if (list2 == null) {            return list1;        }                ListNode newHead = (list1.val <= list2.val) ? list1 : list2;        if (list1.val <= list2.val) {            newHead = list1;            list1 = list1.next;    //无需加上newHead.next = null; 因为此场景不可能出现环        } else {            newHead = list2;            list2 = list2.next;        }        ListNode newTail = newHead;                while (list1 != null && list2 != null) {            if (list1.val <= list2.val) {                newTail.next = list1;                list1 = list1.next;            } else {                newTail.next = list2;                list2 = list2.next;            }            newTail = newTail.next;        }        if (list1 != null) {            newTail.next = list1;        } else {            newTail.next = list2;        }        return newHead;    }        public ListNode Merge1(ListNode list1,ListNode list2) {        if (list1 == null) {            return list2;        }        if (list2 == null) {            return list1;        }                ListNode newHead = null, newTail = null;        while (list1 != null && list2 != null) {            if (list1.val <= list2.val) {                if (newHead == null) {                    newHead = list1;                    newTail = list1;                } else {                    newTail.next = list1;                    newTail = list1;                }                list1 = list1.next;            } else {                if (newHead == null) {                    newHead = list2;                    newTail = list2;                } else {                    newTail.next = list2;                    newTail = list2;                }                list2 = list2.next;            }        }        if (list1 != null) {            newTail.next = list1;        }        if (list2 != null) {            newTail.next = list2;        }        return newHead;    }}

 

转载地址:http://ifnii.baihongyu.com/

你可能感兴趣的文章
Node.js-模块和包
查看>>
Node.js核心模块
查看>>
express的应用
查看>>
NodeJS开发指南——mongoDB、Session
查看>>
Express: Can’t set headers after they are sent.
查看>>
2017年,这一次我们不聊技术
查看>>
实现接口创建线程
查看>>
Java对象序列化与反序列化(1)
查看>>
HTML5的表单验证实例
查看>>
JavaScript入门笔记:全选功能的实现
查看>>
程序设计方法概述:从面相对象到面向功能到面向对象
查看>>
数据库事务
查看>>
JavaScript基础1:JavaScript 错误 - Throw、Try 和 Catch
查看>>
SQL基础总结——20150730
查看>>
SQL join
查看>>
JavaScript实现页面无刷新让时间走动
查看>>
CSS实例:Tab选项卡效果
查看>>
前端设计之特效表单
查看>>
前端设计之CSS布局:上中下三栏自适应高度CSS布局
查看>>
Java的时间操作玩法实例若干
查看>>