[LeetCode] 024. Swap Nodes in Pairs (Medium) (C++/Python)

索引:[LeetCode] Leetcode 题解索引 (C++/Java/Python/Sql)
Github: https://github.com/illuz/leetcode


024. Swap Nodes in Pairs (Medium)

链接

题目:https://oj.leetcode.com/problems/swap-nodes-in-pairs/
代码(github):https://github.com/illuz/leetcode

题意

把一个链表中的每一对节点对换(不能只换值)。

分析

直接模拟即可。
开个前节点来做会比较方便。
用 Python 的异常处理和赋值会很方便。

代码

C++:

class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
		ListNode *newHead = new ListNode(0);
		newHead->next = head;
		ListNode *preNode = newHead, *curNode = head;
		int cnt = 1;
		while (curNode != NULL && curNode->next != NULL) {
			// swap curNode and curNode->next
			preNode->next = curNode->next;
			curNode->next = preNode->next->next;
			preNode->next->next = curNode;
			
			// go over two nodes
			preNode = curNode;
			curNode = curNode->next;
		}
		head = newHead->next;
		delete newHead;
		return head;
    }
};


Python:

class Solution:
    # @param a ListNode
    # @return a ListNode
    def swapPairs(self, head):
        dummy = ListNode(0)
        dummy.next = head
        cur = dummy

        try:
            while True:
                pre, cur, nxt = cur, cur.next, cur.next.next
                # change the position of cur and nxt
                pre.next, cur.next, nxt.next = nxt, nxt.next, cur
                # now cur is in the third place
        except:
            return dummy.next



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值