加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 20:05:07 所属栏目:PHP教程 来源:网络整理
导读:索引:[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/l

索引:[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

题意

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

分析

直接摹拟便可。
开个前节点来做会比较方便。
用 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,nxt.next = nxt,nxt.next,cur # now cur is in the third place except: return dummy.next



(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读