Swap Nodes in pairs--problem solving report

Source: Internet
Author: User


Topic

Given a linked list, swap every, adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. Modify the values in the list, only nodes itself can be changed.


Analysis

Using recursive resolution, the first step out of the recursive condition must be the remaining length of the list is 0 or 1, that is, head = = Null,head->next = NULL. Second, be sure to pay attention to the list of remaining nodes in the case of reversing two nodes, otherwise, head->next are empty, how to reverse the back node? See the note below for details.


Code

Run Time 4ms


/** * Definition for singly-linked list. * struct ListNode {*     int val; *     ListNode *next; *     listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public:    listnode* swappairs (listnode* head) {                if (head = = NULL | | head->next = = NULL)  //recursive bounce condition            ret URN Head;        listnode* tmp = Swappairs (head->next->next);  Must be in front recursion, if the head->next are empty, recursive into can be seen, but the following directly to Head->next will not be judged.        listnode* res = head->next;        Res->next = head;        Res->next->next = tmp;        return res;    }};


Swap Nodes in pairs--problem solving report

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.