力扣24.两两交换链表中的节点

力扣24. 两两交换链表中的节点


一、题目

请添加图片描述

二、图解

解释: 这题目我们首先需要用到三个指针pre, cur, next 进行对两个节点进行交换。
首先先说一下简单的节点交换原理,如下图所示,cur是当前节点,next是下一个节点,我们要让 当前节点cur的下一个指针指向下下个指针,则让cur.next = next.next, 让next.next = cur,这样就产生了对换,还有一个步骤就是要让pre的next指向next,这里是头部,有两个重点,一是要修改head,head = cur,二是让pre是null,因此pre没有next。然后让pre=cur,cur=next,现在还要判断cur是否为null,因为cur是null的话说明以及没有节点要交换了,若cur不为null则让next=cur.next 再继续判定。整个循环是通过判定cur和next是否为null
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

三、源码

代码如下(示例):

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return head;
        }
        ListNode pre = null;
        ListNode cur = head;
        ListNode next = head.next;
        while(cur != null && next != null){
            cur.next = next.next;
            next.next = cur;
            if(pre != null){
                pre.next = next;
            }else{
                head = next;
            }
            pre = cur;
            cur = pre.next;
            if(cur != null){
                next = cur.next;
            }
        }
        return head;

    }
}
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值