zoukankan      html  css  js  c++  java
  • 链表四:合并两个排序的链表

    /**
     * 题目:合并两个排序的链表
     * 描述:输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
     * 解决方案:
     * */

    public class Four {
        //递归
        public static ListNode one(ListNode listOne,ListNode listTwo) {    
            if(listOne == null ) {
                return listTwo;
            }
            if(listTwo == null ) {
                return listOne;
            }
            ListNode head = null;
            if(listOne.var <listTwo.var) {
                head = listOne;
                head.next =one(listOne.next,listTwo);
            }else {
                head = listTwo;
                head.next = one(listOne,listTwo.next);
            }        
            return head;
        }
    
        //非递归
        public static ListNode two(ListNode listOne,ListNode listTwo) {    
            if(listOne == null ) {
                return null;
            }
            if(listTwo == null ) {
                return null;
            }
            ListNode temp = null;
            if(listOne.var < listTwo.var ) {
                temp =listOne;
                listOne = listOne.next;//将当前节点的后一个节点赋值给listOne
            }else {
                temp =listOne;
                listOne = listOne.next;
            }
            while(listOne!=null && listTwo != null) {
                if(listOne.var < listTwo.var) {
                    temp.next = listOne;
                    listOne = listOne.next;
                }else {
                    temp.next = listTwo;
                    listTwo = listTwo.next;
                }
            }
            return temp;
            
        }
        
        class ListNode{
            int var;
            ListNode next;
        }
    
    }
    天助自助者
  • 相关阅读:
    【一篇文章就够了】Apollo
    【一篇文章就够了】Redis入门
    使用IDEA学习廖雪峰官方Git教程
    SourceTree的使用介绍
    【黑马旅游网】总结
    Entity Framework数据迁移命令使用总结
    leetcode editor
    IDEA个性化配置
    mysql5.7驱动(tableau,excel)
    正则表达式(1)
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969336.html
Copyright © 2011-2022 走看看