题目: 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.

分析:简单题。

处理链表一定要注意的几点:

  • 如果处理的是头节点,通常要可能会做特殊处理。
  • 保留prev指针。
  • 对节点取值前注意会不会是NULL。

这道题的思路是建立两个指针,每个指针对应一个链表,一个指向两个链表中值小的那个,一个指向值大的那个,如果在运行中值小的那个大于了值大的那个,则交换两指针。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode small, ret, big, prev;
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        small = l1.val <= l2.val ? l1 : l2;
        big = small == l1 ? l2 : l1;
        ret = prev = small;

        while (small != null || big != null) {

            if (big == null) {
                while(small != null) small = small.next;
                break;
            }

            while (small != null && small.val <= big.val) {
                prev = small;
                small = small.next;
            }

            prev.next = big;
            big = small;
            small = prev.next;
        }
        return ret;
    }
}

ssnau
1.5k 声望98 粉丝

负能量职业打码师


引用和评论

0 条评论