力扣24题 两两交换链表中的节点 (一看就会,一做就废版)

只能说这个题看起来简单,做起来全是坑

本来以为二十分钟内能够做完,一运行全是坑,后来搞了一个小时才做对,好好好!

最开始的思路是不设置虚拟头结点,使用cur和next遍历,每次循环交换cur和next,但是这种思路存在问题,**会缺失节点!!**这个思路的示意图如下,可以看到第二次循环时,节点4被丢失了。
在这里插入图片描述
于是设置了虚拟节点,第一次代码如下(报错代码),代码执行while (cur.next.next != null && cur.next != null)会出现空指针异常。

public ListNode swapPairs2(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode cur = dummyNode;
        ListNode temp;  //记录两个节点后边的节点
        ListNode firstNode;//记录要交换的连个节点的第一个节点
        ListNode secondNode;//记录要交换的连个节点的第二个节点
        while (cur.next.next != null && cur.next != null){
            firstNode = cur.next;
            secondNode = cur.next.next;
            temp = cur.next.next.next;
            cur.next = secondNode;
            secondNode.next = firstNode;
            firstNode.next = temp;
            cur = firstNode;
        }
        return dummyNode.next;
    }

仔细分析后发现,需要把cur.next.next != null && cur.next != null两个条件交换,也就是括号里边需要这么写 cur.next != null && cur.next.next != null。

为什么要交换?
当链表有偶数个节点时,最后一次循环cur到达最后一个节点,此时cur.next == null,但是由于cur.next.next != null条件在前边,程序先运行该条件,此时便会出现空指针异常。
由此也能够分析出条件运算符只能够使用&&,不能使用&,因为&符号两边的程序都会被运行,&&会先判断左边表达式,左边表达式为false则不会运行右边。

不得不感慨程序语法的每个运算符都是有用的,之前还一直不理解为什么要发明一个&&运算符

行行行,算这道题厉害

最终的思路和代码见下:
在这里插入图片描述

public ListNode swapPairs2(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }
        ListNode dummyNode = new ListNode(-1);
        dummyNode.next = head;
        ListNode cur = dummyNode;
        ListNode temp;  //记录两个节点后边的节点
        ListNode firstNode;//记录要交换的连个节点的第一个节点
        ListNode secondNode;//记录要交换的连个节点的第二个节点
        while (cur.next != null && cur.next.next != null){
            firstNode = cur.next;
            secondNode = cur.next.next;
            temp = cur.next.next.next;
            cur.next = secondNode;
            secondNode.next = firstNode;
            firstNode.next = temp;
            cur = firstNode;
        }
        return dummyNode.next;
    }
  • 15
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值