24. Swap Nodes in Pairs

题目要将相邻两个节点交换但是不能只交换数值。

1. 我的方法 循环

  1)需要注意判断是否是null,凡是要调用next就要注意了!

   2)注意交换两个节点之后,node指向的下一个并不是当前后面链表的头(因为后面也要交换),所以应该判断下后面会不会继续交换,如果是的话就要指向下下个,不然就直接指向下一个。

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode node = head;
        if(node==null || node.next==null)
            return node;
        ListNode pre = new ListNode(0);
        pre.next = node.next;
        while(node!=null && node.next!=null){
            ListNode tmp = node.next.next;
            node.next.next = node;
            if(tmp!=null &&tmp.next != null)
                node.next = tmp.next;//这几行对应第二个注意点
            else 
                node.next = tmp;
            node = tmp;
        }
        return pre.next;
    }
}

2. 使用递归

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值