leetcode_swapPairs关于链表.next一不小心就犯错的问题

        关于链表head.next.next==p.next,最后一个.next在等号左边相等于指向,等号右边的.next代表下一个节点,所以就相当于head的下一个节点指向了p的下一个节点,然后在代码比较复杂点的情况下,应该定义临时变量引用,以免出不必要的错。

//给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
public class swapPairs {
    public static ListNode swapPairs1(ListNode head) {
        //开始前:1->2->3->4->null
        if (head == null || head.next == null)
            return head;
        ListNode q=head.next;
        ListNode p = head.next.next;//p->3
       // head.next = head.next.next;//1->3
        head.next=swapPairs1(p);
        q.next = head;//2->1
        //2->1->3->4
        //再将p节点带入递归

        return q;//最后返回的是2这个节点
        //最终想要达到的效果:2->1->4->3->null
    }
    public static ListNode swapPairs_defeat(ListNode head) {
        //开始前:1->2->3->4->null
        if (head == null || head.next == null)
            return head;
        ListNode p = head.next.next;//p->3
        head.next = head.next.next;//1->3
        //此时1->3了,那么下面这行代码就有问题了,相当于3->1了。
        head.next.next = head;//2->1
        //2->1->3->4
        //再将p节点带入递归
        head.next=swapPairs(p);
        return head.next;//最后返回的是2这个节点//也是3这个节点,链表题目应该注意下当代码较为复杂的时候应该用临时变量引用
        //最终想要达到的效果:2->1->4->3->null
    }
        public static ListNode swapPairs2(ListNode head) {
            if(head == null || head.next == null)
                return head;
            ListNode temp = head.next;
            head.next = swapPairs2(head.next.next);
            temp.next = head;
            return temp;
        }


    public static void ListNodetoString(ListNode node){
        while (node!=null){
            System.out.print(node.val+" ");
            node=node.next;
        }
    }
    public static void main(String[] args) {
        ListNode list1=new ListNode(1,new ListNode(2,new ListNode(3,new ListNode(4,null))));
        ListNode list2=new ListNode(1,new ListNode(3,new ListNode(4,null)));
        ListNodetoString(swapPairs2(list1));
        ListNodetoString(swapPairs1(list1));
        //System.out.println(mergeTwoLists(list1,list2).toString());
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值