代码:
package com.me.leetcode;
public class Sloution {
public static void main(String[] args) {
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node1 = swapPairs(node1);
node1.println();
}
public static ListNode swapPairs(ListNode head) {
// 如果节点为null,或者节点的下一个节点也为空,则无交换的意义,返回node
if (head == null || head.next == null) {
return head;
}
// 把下下一个节点递归下去交换
ListNode newNode = swapPairs(head.next.next);
// 交换当前的两个节点
ListNode temp = head;
head = head.next;
head.next = temp;
// 把递归返回的节点挂在交换后的第二个节点后面
head.next.next = newNode;
return head;
}
public static class ListNode {
int data;
ListNode next;
public ListNode(int data) {
this.data = data;
}
public void println() {
ListNode index = this;
while (index != null) {
System.out.print(index.data + " ");
index = index.next;
}
System.out.println();
}
}
}
Q.E.D.