Swap Nodes in Pairs

主框架就是遍历,循环条件是p && p->next,保证有2个node.

循环体的逻辑:主要变量:当前要交换的node, p, p->next, 左边连接的节点prev, 右边连接的节点,要做的事就是交换两个节点,并且处理好左边和右边与外部链表的连接。

 ListNode *swapPairs(ListNode *head) {
        ListNode dummy(-1);
    	dummy.next=head;
    	ListNode *prev=&dummy, *p=head;
    
    	while(p && p->next)
    	{
    		ListNode* second= p->next; //keep the right outer node
    		p->next=second->next; //connect the 1st node to the right outer node
    		second->next=p; //connect the 2nd node to the 1st node
    		prev->next=second; // connect the left outer node to the 2nd node
    		prev=p; //update left outer node
    		p=p->next;// update the current pointer
    	}
    	return dummy.next;
    }


用合适的变量名,使得指针清晰

ListNode *swapPairs(ListNode *head) {
    ListNode dummy(-1), *prev = &dummy;
    dummy.next = head;
    for (ListNode *second, *third; head && head->next; prev = head, head = third) {
        second = head->next, third = second->next;
        second->next = head;
        head->next = third;
        prev->next = second;
    }
    return dummy.next;
}


还是递归版本清晰:

ListNode *swapPairs(ListNode *head) {
    if (!head || !head->next) return head;
    auto second = head->next, third = second->next;
    second->next = head;
    head->next = swapPairs(third);
    return second;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值