21. Merge Two Sorted Lists

Posted optor

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了21. Merge Two Sorted Lists相关的知识,希望对你有一定的参考价值。

原题链接:https://leetcode.com/problems/merge-two-sorted-lists/description/
这道题目是合并两个有序的单链表。。。尼玛,这不就是《数据结构(C语言版)》上的原题嘛,并不是考察什么高超的算法,就是普通的链表操作知识而已!

import java.util.Stack;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(3);
        l1.next.next = new ListNode(5);
        l1.next.next.next = new ListNode(8);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(2);
        l2.next.next = new ListNode(3);
        l2.next.next.next = new ListNode(6);

        ListNode res = s.mergeTwoLists(l1, l2);
        System.out.println(res);
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode root = new ListNode(0);
        ListNode temp = root;

        ListNode m = l1;
        ListNode n = l2;

        while (m != null && n != null) {
            if (m.val > n.val) {
                temp.next = n;
                n = n.next;

            } else {
                temp.next = m;
                m = m.next;
            }
            temp = temp.next;
        }

        if (m != null) { // so n is null
            temp.next = m;
        }
        if (n != null) { // so m is null
            temp.next = n;
        }

        return root.next;
    }

}

以上是关于21. Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

21. Merge Two Sorted Lists

[LeetCode] 21. Merge Two Sorted Lists_Easy tag: Linked List

LeetCode(21) - Merge Two Sorted Lists

21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

LintCode - Merge Two Sorted List