Merge Two Sorted Lists

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;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(-1);
        ListNode rst = dummy;
        while(l1 != null && l2 != null)
        {
            int val1 = l1.val;
            int val2 = l2.val;
            if(val1 < val2)
            {
                dummy.next = l1;
                l1 = l1.next;
            }
            else
            {
                dummy.next = l2;
                l2 = l2.next;
            }
            dummy = dummy.next;
        }
        while(l1 != null)
        {
            dummy.next = l1;
            l1 = l1.next;
            dummy = dummy.next;
        }
        while(l2 != null)
        {
            dummy.next = l2;
            l2 = l2.next;
            dummy = dummy.next;
        }
        return rst.next;
    }
}
View Code

他人代码:

public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode lastNode = dummy;
        
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                lastNode.next = l1;
                l1 = l1.next;
            } else {
                lastNode.next = l2;
                l2 = l2.next;
            }
            lastNode = lastNode.next;
        }
        
        if (l1 != null) {
            lastNode.next = l1;
        } else {
            lastNode.next = l2;
        }
        
        return dummy.next;
    }
}
View Code

学习之处:

  • 链表不同之处在于最后做收尾工作的时候,不用再继续循环了,直接if else就OK了,数组不同于链表啊,我的代码中在这一部分浪费了很多时间

 

posted on 2015-03-06 16:58  zhouzhou0615  阅读(104)  评论(0编辑  收藏  举报

导航