个人记录-LeetCode 21. Merge Two Sorted Lists

问题:
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

合并两个排序的链表。

这个问题唯一的陷阱是:没有指定链表是按升序还是降序排列。

代码示例:

/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //判断是否按照升序排列
        boolean isFirstASC = isAscList(l1);
        boolean isSecondAsc = isAscList(l2);

        //不是升序排列,就转化为升序排列
        if (!(isFirstASC && isSecondAsc)) {
            if (!isFirstASC) {
                l1 = changeDscToAsc(l1);
            } else {
                l2 = changeDscToAsc(l2);
            }
        }

        //合并升序链表
        return mergeAscLists(l1, l2);
    }

    private boolean isAscList(ListNode l) {
        boolean isASC = true;

        if (l != null && l.next != null) {
            if (l.val > l.next.val) {
                isASC = false;
            }
        }

        return isASC;
    }

    private ListNode mergeAscLists(ListNode l1, ListNode l2) {
        ListNode temp = new ListNode(0);
        ListNode result = temp;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                temp.next = l1;
                l1 = l1.next;
            } else {
                temp.next = l2;
                l2 = l2.next;
            }
            temp = temp.next;
        }

        if (l1 != null) {
            temp.next  = l1;
        } else {
            temp.next = l2;
        }

        return result.next;
    }

    private ListNode changeDscToAsc(ListNode l) {
        Stack<Integer> stack = new Stack<>();
        while (l != null) {
            stack.push(l.val);
            l = l.next;
        }

        ListNode temp = new ListNode(0);
        ListNode result = temp;
        while (!stack.empty()) {
            temp.next = new ListNode(stack.pop());
            temp = temp.next;
        }

        return result.next;
    }
}

你可能感兴趣的:(个人记录-LeetCode 21. Merge Two Sorted Lists)