Board logo

标题: Leetcode - Merge Two Sorted Lists 更新 [打印本页]

作者: look_w    时间: 2019-2-18 19:35     标题: Leetcode - Merge Two Sorted Lists 更新

My test result:
161212-613170b3742bbe2f.png
Paste_Image.png

和之前的差不多做法,还是比较简单的,除了要处理一些细节问题。

补:只不过可以看出一个明显的问题,头结点需要用if语句来确定,逻辑要麻烦一点。然后网上无意间看到了一个做法,叫做 Dummy Node, 很好,分享如下。

    private ListNode merge(ListNode head1, ListNode head2) {
             ListNode dummy = new ListNode(-1);
             ListNode head = dummy;
             while (head1 != null && head2 != null ) {
                if (head1.val < head2.val) {
                    head.next = head1;
                    head1 = head1.next;
                }else {
                    head.next = head2;
                    head2 = head2.next;
                }
                head = head.next;
               
            }
             if (head1 != null) {
                        head.next = head1;
              }
             else {
                    head.next = head2;
              }
            return dummy.next;
        }

161212-45c3094abdf5f9fc.png
Paste_Image.png

**
总结: Array
**

Anyway, Good luck, Richardo!

My code:

    /**
     * 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) {
            if (l1 == null)
                return l2;
            else if (l2 == null)
                return l1;
            ListNode dummy = new ListNode(-1);
            ListNode temp = dummy;
            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;
            }
            temp.next = (l1 == null) ? l2 : l1;
            return dummy.next;
        }
    }

没什么难的。

Anyway, Good luck, Richardo!

差不多的做法。。
想当年, dummy node也不知道啊。
只不过知道了也没多大用。

Anyway, Good luck, Richardo! -- 08/15/2016




欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) Powered by Discuz! 7.0.0