Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode
024. Swap Nodes in Pairs (Medium)
links:
Title: https://oj.leetcode.com/problems/swap-nodes-in-pairs/
Code (GitHub): Https://github.com/illuz/leetcode
Test Instructions:
Swap each pair of nodes in a list (not just the value).
Analysis:
Direct simulation can be done.
It would be convenient to open a front node to do it.
It is convenient to use Python for exception handling and assignment.
Code:
C++:
Class Solution {public: listnode *swappairs (ListNode *head) {ListNode *newhead = new ListNode (0); Newhead->next = h ead ListNode *prenode = newhead, *curnode = head;int cnt = 1;while (Curnode! = NULL && Curnode->next! = null) {//S WAP Curnode and curnode->nextprenode->next = Curnode->next;curnode->next = prenode->next->next; Prenode->next->next = curnode;//go over the Nodesprenode = 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 # Chang E The position of cur and nxt pre.next, cur.next, Nxt.next = NXT, nxt.next, cur # now cur are in the third place< C12/>except: return Dummy.next
[Leetcode] 024. Swap Nodes in Pairs (Medium) (C++/python)