[LeetCode]Swap Nodes in Pairs

本文提供了两种链表(单向和双向)中节点成对交换的解决方案,通过自定义链表节点类,实现了一种迭代算法,有效地完成了节点的交换,并保持了链表的连续性和正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上面是lc的单链表题目,下面我又自己加了个双向链表的情况

 

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        ListNode pre = head;
        ListNode p1 = head.next;
        ListNode p2 = head.next.next;
        ListNode p3 = head.next.next.next;
        while (p1 != null && p2 != null) {
            p1.next = p3;
            p2.next = p1;
            pre.next = p2;
            pre = p1;
            p1 = p3;
            if (p1 == null) {
                break;
            }
            p2 = p1.next;
            if (p2 == null) {
                break;
            }
            p3 = p2.next;
        }
        return head.next;
    }
}

 

 

 

public class Solution {
    public duListNode solution (duListNode head, duListNode end) {
        if (head == null || head.next == null) {
            return head;
        }
        duListNode dummy = new duListNode(0);
        dummy.next = head;
        head = dummy;
        dummy = new duListNode(0);
        end.next = dummy;
        dummy.pre = end;
        end =  end.next;
        duListNode p1 = head;
        duListNode p2 = head.next;
        duListNode p3 = head.next.next;
        duListNode p4 = head.next.next.next;
        while (p2 != null && p3 != null) {
            p2.next = p4;
            p4.pre = p2;
            p1.next = p3;
            p3.pre = p1;
            p3.next = p2;
            p2.pre = p3;
            if (p4 == end || p4.next == end) {
                break;
            }
            p1 = p2;
            p2 = p4;
            p3 = p4.next;
            p4 = p3.next;
        }
        end = end.pre;
        end.next = null;
        return head.next;
        
    }
}



public class duListNode {
    int val;
    duListNode next;
    duListNode pre;
    duListNode (int val) {
        this.val = val;
    }
}

 

转载于:https://www.cnblogs.com/vision-love-programming/p/5020938.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值