zoukankan      html  css  js  c++  java
  • 合并两个排序的链表

    输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

    示例1:

    输入:1->2->4, 1->3->4
    输出:1->1->2->3->4->4

    
    
    class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
    val = x;
    }
    }



    public class
    Solution { public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); Solution solution = new Solution(); ListNode listNode = solution.mergeTwoLists(l1, l2); while (listNode!=null){ System.out.println(listNode.val); listNode = listNode.next; } } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newHead = new ListNode(-1); ListNode newHeadPoint = newHead; while (l1!=null || l2!=null){ if (l1==null){ newHeadPoint.next = l2; break; } if (l2==null) { newHeadPoint.next = l1; break; } if (l1.val < l2.val){ newHeadPoint.next = l1; newHeadPoint = newHeadPoint.next; l1 = l1.next; continue; } else { newHeadPoint.next = l2; newHeadPoint = newHeadPoint.next; l2 = l2.next; continue; } } return newHead.next; } }
  • 相关阅读:
    macOS 修改键盘重复按键延迟
    stdout 与 stderr 区别
    E. 1-Trees and Queries
    Codeforces Round #615 (Div. 3)
    Codeforces Round 613(div 2)
    Codeforces Edu80
    SPOJ
    快读
    《货车运输》题解--最大生成树&倍增
    倍增思想求lca
  • 原文地址:https://www.cnblogs.com/iuyy/p/13687560.html
Copyright © 2011-2022 走看看