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;
            }
        }
    }
    
  • 相关阅读:
    c++11之智能指针
    SurfaceFlinger与Surface概述
    android GUI 流程记录
    文章收藏
    android performance
    POJ3349
    java中的volatile和synchronized
    [原创]分期还款的名义利率与真实利率
    Java IO 流总结
    telegram
  • 原文地址:https://www.cnblogs.com/ITxiaolei/p/13166982.html
Copyright © 2011-2022 走看看