zoukankan      html  css  js  c++  java
  • 剑指offer:面试题17、合并两个排序的链表

    题目描述

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

    代码示例

    public class Offer17 {
        public static void main(String[] args) {
            ListNode l1 = new ListNode(1);
            l1.next = new ListNode(2);
            l1.next.next = new ListNode(2);
            ListNode l2 = new ListNode(3);
            l2.next = new ListNode(4);
            Offer17 testObj = new Offer17();
            testObj.printList(l1);
            testObj.printList(l2);
    //        testObj.printList(testObj.mergeTwoList(l1,l2));
            testObj.printList(testObj.mergeTwoList2(l1,l2));
    
        }
    
        //递归合并两个链表
        public ListNode mergeTwoList(ListNode l1, ListNode l2) {
            if (l1 == null) {
                return l2;
            }
            if (l2 == null) {
                return l1;
            }
    
            if (l1.val <= l2.val) {
                l1.next = mergeTwoList(l1.next, l2);
                return l1;
            } else {
                l2.next = mergeTwoList(l1, l2.next);
                return l2;
            }
        }
    
        //迭代合并两个链表
        public ListNode mergeTwoList2(ListNode l1, ListNode l2) {
            ListNode head = new ListNode(-1);
            ListNode cur = head;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
            if (l1 != null)
                cur.next = l1;
            if (l2 != null)
                cur.next = l2;
            return head.next;
        }
        //打印链表
        public void printList(ListNode head) {
            if (head == null) {
                return;
            }
            while (head != null) {
                System.out.print(head.val + " ");
                head = head.next;
            }
            System.out.println();
        }
    
        static class ListNode {
            int val;
            ListNode next;
            ListNode(int val) {
                this.val = val;
            }
        }
    }
    
  • 相关阅读:
    函数封装总结
    03.深入javascript
    02.JavaScript基础下
    html5权威指南:客户端分区响应图
    html5权威指南:定制input元素
    html5权威指南:表单元素
    html5权威指南:表格元素
    html5权威指南:组织内容、文档分节
    css布局理解
    html5权威指南:标记文字
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13166982.html
Copyright © 2011-2022 走看看