zoukankan      html  css  js  c++  java
  • <剑指offer> 第14题

    题目:

    输入两个递增序列的链表,合并这两个链表并使新链表中的节点仍然为按照递增顺序的。

    思路:

    (1)定义一个指向新链表的指针,暂且让它指向NULL

    (2)比较两个链表的头节点,让较小的头节点作为新链表的头节点

    (3)a:循环比较两个链表的其余节点,让较小的节点作为上一新节点的后一个节点。直到有一个链表没有节点,然后将新链表的最后一个节点直接指向剩余链表的节点。

       b:递归比较两个链表的其余节点,让较小的节点作为上一个新节点的后一个节点

    代码实现:

    public class Fourteenth {
    
        public class ListNode{
            ListNode next;
            int val;
        }
    
        public ListNode sortTwoList(ListNode head1, ListNode head2){
            if(head1 == null){
                return head2;
            }
            if(head2 == null){
                return head1;
            }
         //合成链表的头节点 ListNode root
    = new ListNode();
    //当前合成链表的最后一个指针 ListNode pointer
    = root; while(head1 != null && head2 != null){ if(head1.val < head2.val){ pointer.next = head1; head1 = head1.next; }else{ pointer.next = head2; head2 = head2.next; } pointer = pointer.next; } if(head1 != null){ pointer.next = head1; } if(head2 != null){ pointer.next = head2; } return root.next; } public static ListNode merge(ListNode head1, ListNode head2){ if(head1 == null){ return head2; } if(head2 == null){ return head1; } //记录两个链表中头部较小的节点 ListNode tmp = head1; if(tmp.val < head2.val){ tmp.next = merge(head1.next, head2); }else{ tmp = head2; tmp.next = merge(head1, head2.next); } return tmp; } }
  • 相关阅读:
    数据库chapter 4 数据库安全性
    数据库 chapter 2 关系数据库
    数据库 chapter 1 概论
    操作系统 chapter 11 I/O系统
    操作系统 chapter 12 死锁
    操作系统 chapter 7 8 存储模型
    聊一聊移动调试那些事儿
    获取当前日期和农历的js代码
    使用 CSS 媒体查询创建响应式网站
    大前端工具集
  • 原文地址:https://www.cnblogs.com/HarSong13/p/11329635.html
Copyright © 2011-2022 走看看