您的位置:首页 > Web前端 > Node.js

LeetCode 24 Swap Nodes in Pairs (交换相邻节点)

2017-03-09 19:35 561 查看
题目链接: https://leetcode.com/problems/swap-nodes-in-pairs/?tab=Description

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: