/**
* @Class Swap
* @Description 24. 两两交换链表中的节点
* 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
*
* 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
*
* 示例 1:
* 输入:head = [1,2,3,4]
* 输出:[2,1,4,3]
* 示例 2:
* 输入:head = []
* 输出:[]
* 示例 3:
* 输入:head = [1]
* 输出:[1]
*
* 提示:
* 链表中节点的数目在范围 [0, 100] 内
* 0 <= Node.val <= 100
*
* @Author Administrator
* @Date 2020/12/2 21:15
**/
public class Swap {
static class ListNode {
private int value;
private ListNode next;
public ListNode(int value) {
this.value = value;
next = null;
}
}
/*
* 递归
*/
public static ListNode getReverse(ListNode head) {
if (head == null || head.next == null) return head;
ListNode newNode = head.next;
head.next = getReverse(head.next.next);
newNode.next = head;
return newNode;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
ListNode listNode2 = new ListNode(2);
ListNode listNode3 = new ListNode(3);
ListNode listNode4 = new ListNode(4);
ListNode listNode5 = new ListNode(5);
head.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
ListNode ansListNode = getReverse(head);
while (ansListNode != null) {
System.out.print(" " + ansListNode.value);
ansListNode = ansListNode.next;
}
}
}