Leetcode #24 Swap Nodes in Pairs (M)

Source: Internet
Author: User

[Problem]

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]

This problem can be solved simply by using recursion, but the process of thinking is a bit of a detour. The topic requirements can not change the value of the list, that is, only on the pointer on the node, observing the law, you can find that the need to do is to two node interchange position, and next set to the next set of two nodes after the first, thus constituting a recursive solution.

[Solution]

 Public class Solution {    public  ListNode swappairs (ListNode head) {        ifnull NULL ) {            return  head;        }                 = Head.next;                         = Swappairs (head.next.next);         = head;                 return node;    }}

Leetcode #24 Swap Nodes in Pairs (M)

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.