[Leetcode] 024. Swap Nodes in Pairs (Medium) (C++/python)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.