码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 24 Swap Nodes in Pairs

时间:2017-03-09 20:59:40      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:否则   .com   version   1.0   utf-8   script   ack   https   ppa   

 
Problem: 交换相邻的两个节点
 
技术分享
 
  如上图所示,递归进行交换。从最尾端开始,当最尾端只有一个节点时,停止交换
  否则执行 swap(head.next) 
 
参考代码:
 
package leetcode_50;

/**
 * 
 * @author pengfei_zheng
 * 交换相邻节点
 */
public class Solution24 {
    public class ListNode {
          int val;
          ListNode next;
          ListNode(int x) { val = x; }
      }
     
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}

 

 

LeetCode 24 Swap Nodes in Pairs

标签:否则   .com   version   1.0   utf-8   script   ack   https   ppa   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6527363.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!