Swap Nodes in Pairs 交换LinkList的相邻节点

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

解决link list类的问题可以分为两步。

第一步,找出第一阶段的指针该怎么变换。

第二步,找出怎么移动指针到下一阶段。

先来看第一步。

我是利用3个指针来控制,cur指向偶数位的节点(这里是2),pre指向cur的前面一个节点(1),prepre 指向 pre的前面一个节点(一开始让prepre指向伪造的头节点fakeNode)。

如何实现交换?让2指向1,1指向3-> 4就可以了,同时让prepre 指向 2, 将各部分串联起来。

pre.next = cur.next;
cur.next = pre;
prepre.next = cur;

接下来是第二部,指针该怎么移动。

翻转完1,2就轮到3,4了,我们想让cur指向4,pre指向3,prpre指向1

 prepre = pre;
cur = pre.next.next;
pre = pre.next;

关键:手动模拟!

运行时间:


代码:

public class SwapNodesinPairs {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode fakeNode = new ListNode(-1);
        fakeNode.next = head;
        ListNode prepre = fakeNode, pre = head, cur = head.next;
        while (cur != null) {
            pre.next = cur.next;
            cur.next = pre;
            prepre.next = cur;
            if (pre.next == null || pre.next.next == null) {
                break;
            } else {
                prepre = pre;
                cur = pre.next.next;
                pre = pre.next;
            }
        }
        return fakeNode.next;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值