栈和队列----合并两个有序的单链表

合并两个有序的单链表

  

  给定两个有序单链表的头节点 head1 和 head2,合并两个有序链表,合并后链表依然有序,并返回合并后的链表的头节点,例如:0->2->3->7->null   和   1->3->5->7->9->null,合并后的链表为 0->1->2->3->3->5->7->7->9->null。

 

  【解题思路】

  如果两个链表的长度分别为M 和 N ,那么时间复杂度可以做到 O(M+N),空间复杂度可以做到O(1)

  1. 如果有一个为空,直接返回另一个

  2. 比较两个头节点的值,较小的作为新的头节点

  3. 每次比较时,cur1和cur2 分别表示两个链表的值,pre永远表示上次比较时较小的值

package com.test;

import com.test.ListNode;

/**
 * Created by Demrystv.
 */
public class MergeTwoSortedListNode {

    public ListNode merge(ListNode head1, ListNode head2){

        if (head1 == null | head2 == null){
            return head1 == null ? head2 : head1;
        }

        ListNode head = head1.val < head2.val ? head1 : head2;
        ListNode cur1 = head == head1 ? head1 : head2;
        ListNode cur2 = head == head1 ? head2 : head1;

        ListNode pre = null;
        ListNode next = null;

        while (cur1 != null && cur2 != null){
            if (cur1.val < cur2.val){

                //这两句就是相当于指针的移动
                pre = cur1;
                cur1 = cur1.next;
            }else {

                //这一句就是先保存值
                next = cur2.next;
                //这两句指的是从上面的cur1切换过来,再切换回去
                pre.next = cur2;
                cur2.next = cur1;

                //这两句就是相当于指针的移动
                pre = cur2;
                cur2 = next;
            }
        }

        //针对空的情况做判断
        pre.next = cur1 == null ? cur2 : cur1;
        return head;
    }


}

 

  

转载于:https://www.cnblogs.com/Demrystv/p/9404602.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值