zoukankan      html  css  js  c++  java
  • Merge Two Sorted Lists—LeetCode

    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;
        }
  • 相关阅读:
    ES6 Promise 用法转载
    移动端滚动性能优化
    Python之禅
    Day01~15
    Python
    第一章 Java起源
    IMP-00009: 导出文件异常结束 imp
    浏览器访问网页的详细内部过程
    数据库连接池
    连接数据库 六大步骤
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4356068.html
Copyright © 2011-2022 走看看