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;
        }
    
    }
    天助自助者
  • 相关阅读:
    各种锁
    几百兆的sql文件无法编辑
    og4j1.x升级log4j2.x及异步日志开启
    TSNE/分析两个数据的分布
    _tkinter.TclError: no display name and no $DISPLAY environment variable
    split分割文件
    ubuntu+jdk
    进程操作
    ImportError: No module named apex
    Ubuntu 16.04.4安装Anaconda
  • 原文地址:https://www.cnblogs.com/ZeGod/p/9969336.html
Copyright © 2011-2022 走看看