*LeetCode-Swap Nodes in Pairs

本文详细解析了指针操作中的常见错误,并通过多个测试案例展示了如何正确使用指针解决链表相关问题。从基础知识出发,逐步深入到实际应用,帮助读者提升链表操作能力。

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

指针的判断真的超级容易出错,多想几个test case 1,12,123都想全

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ( head == null || head.next == null )
            return head;
        ListNode dummy = new ListNode(0);
        ListNode pre = dummy;
        ListNode first = head;
        ListNode second = head.next;
        while ( second!= null ){ //这个判断条件错了好几次
            pre.next = second;
            first.next = second.next;
            second.next = first;
            pre = first;
            first = first.next;
            if ( first == null ) //这里要多判断一下
                break;
            second = first.next;
        }
        return dummy.next;
    }
}

几个月前用c++刷的时候

    ListNode *swapPairs(ListNode *head) {
        if ( head == NULL || head->next == NULL)
            return head;
        else {
            ListNode * tempP = head;
            ListNode * tempPNext;
            ListNode *ret=head->next;
            ListNode *last=new ListNode(0);
            while (tempP!= NULL && tempP->next!=NULL ){
                tempPNext = tempP->next;
                last->next=tempPNext;
                tempP->next = tempP->next->next;
                tempPNext->next = tempP;
                last=tempP;
                tempP = tempP->next;
            }
            return ret;
        }
    }

discuss里面的recursive 但是超级难想 而且空间是n

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、付费专栏及课程。

余额充值