首页 > 其他 > 详细

LeetCode #24 Swap Nodes in Pairs (M)

时间:2015-10-24 06:38:54      阅读:260      评论:0      收藏:0      [点我收藏+]

[Problem]

Given a linked list, swap every two 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. You may not modify the values in the list, only nodes itself can be changed.

 

[Analysis]

这题利用递归可以很简洁地解决,只是思考的过程稍微要绕一下。题目要求不能改变list的值,也就是只能在节点的指针上面下手,观察规律,可以发现需要做的是将两个node互换位置,并且将next设置为下一组交换后的两个节点的第一个,由此构成了一个递归的解法。

 

[Solution]

public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        
        ListNode node = head.next;        
        
        head.next = swapPairs(head.next.next);
        node.next = head;
        
        return node;
    }
}

 

LeetCode #24 Swap Nodes in Pairs (M)

原文:http://www.cnblogs.com/zhangqieyi/p/4906091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!