Leetcode Swap Nodes in Pairs

Source: Internet
Author: User

translation
1->2->3->42->1->4->3。你的算法必须使用唯一不变的空间。你也不能修改列表中的值,只有节点本身是可以改变的。
Original
Give a linkedList, swapeveryAdjacent nodes and return  itsHead. For example, Given1-2-3-4, you shouldreturn  the List  as 2-1-4-3.Your algorithm should use onlyconstant Space. May notModify theValuesinch  the List, only nodes itself can is changed.
Analysis

Let's take the example of the 1,2,3,4 given in the topic as a two-part

1,2--3,4

Or I'll draw a diagram to make it more intuitive ...

Code
/** * Definition for singly-linked list. * struct ListNode { *    int val; *    ListNode* next; *    ListNode(int x): val(x), next(NULL) {} * }; */class Solution {public:    swapPairs(ListNode* head) {        ifreturn NULL;        ifreturn head;        ListNode* temp = head->next;        head->next = swapPairs(temp->next);        temp->next = head;        return temp;    }};

Copyright NOTICE: This article is nomasp Couvant original article, without permission is prohibited reprint! Welcome to my blog: http://blog.csdn.net/nomasp

Leetcode Swap Nodes in Pairs

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.