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

这题似乎过于简单,官方都不屑于给出题解。。。
在这里插入图片描述

我的模拟思路

在链表头部搞个哑结点,然后利用两个间隔为2的指针,模拟一下完事儿。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        
        // 处理边界
        if(head == null || head.next == null) return head;
        
        // 先在原始链表的头部添加一个哑结点压压惊
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        // 直接模拟,借助双指针,两个指针间隔2个单位
        ListNode pre = dummyNode;
        ListNode next = dummyNode.next.next;

        while(true) {
            pre.next.next = next.next;
            next.next = pre.next;
            pre.next = next;
            next = next.next;

            if (next.next != null && next.next.next != null) {
                pre = next;
                next = next.next.next;
            }
            else {
                break;
            }
        }
        return dummyNode.next;
    }
}

这里尤其注意:next指针在两个节点位置交换后的位置。

要么就用递归搞搞

注意递归的边界处理

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        // 递归的做法

        // 首先处理边界:没有结点了,或者只剩一个结点了
        if (head == null || head.next == null) {
            return head;
        } else {
            // 否则处理一下当前的两个结点,定义两个指针
            ListNode pre = head;
            ListNode next = head.next;
            
            // 递归进去
            pre.next = swapPairs(next.next);
            next.next = pre;
            return next;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值