码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Two Sorted Lists—LeetCode

时间:2015-03-21 19:53:40      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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.

https://leetcode.com/problems/merge-two-sorted-lists/

题意就是合并两个有序的链表,说实话,这个题我一开始还真有点轻视,不就是merge sort里一步么,但是真写起来代码,发现有点眼高手低了。因为没加头节点,来回的在current和next上操作,这么做也不是不可以,就是一会儿就搞晕了,还有点麻烦,学数据结构的时候,谈到链表,首先要有个头节点,这里我自己创建一个头节点head,还有个工作指针ptr。遍历两个链表哪个值小就append到ptr后面,最后把不为空的append到ptr后面。如果都为空,那么返回也是空。

Talk is cheap。

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {

        ListNode head = new ListNode(0);
        ListNode ptr = head;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                ptr.next = l1;
                l1 = l1.next;
            } else {
                ptr.next = l2;
                l2 = l2.next;
            }
            ptr = ptr.next;
        }
        ptr.next = l1 == null ? l2 : l1;
        return head.next;
    }

 

Merge Two Sorted Lists—LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4356068.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!