zoukankan      html  css  js  c++  java
  • 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了,数组不同于链表啊,我的代码中在这一部分浪费了很多时间
  • 相关阅读:
    python2.7学习记录之三
    编程题
    解题的小问题(C++)
    算法入门(C++)
    逻辑回归
    入门级(python)
    python2.7学习记录之二
    sql语句-排序后加入序号再运算判断取想要的项
    linux中c多线程同步方法
    进程间的通讯方式
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4318724.html
Copyright © 2011-2022 走看看