[LeetCode] 024. Swap Nodes in Pairs (Medium) (C++/Python)
來源:程序員人生 發布時間:2015-04-08 08:33:50 閱讀次數:2487次
索引:[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, cur.next, nxt.next = nxt, nxt.next, cur
# now cur is in the third place
except:
return dummy.next
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈