最后一遍-L24-Swap Nodes in Pairs
Given a linked list,
swap every two adjacent nodes and return its head.
You must solve the problem without modifying the values in the list's nodes
(i.e., only nodes themselves may be changed.)
Example 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Constraints:
* The number of nodes in the list is in the range [0, 100].
* 0 <= Node.val <= 100
链表的翻转的控制,迭代的训练的内容,有一个通用的解法
import util.ListNode;
public class Solution {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next=new ListNode(2);
head.next.next=new ListNode(3);
head.next.next.next=new ListNode(4);
head.next.next.next.next=new ListNode(5);
System.out.println(swapPairs(head));
}
/**
* @param head
* 1--> 2--> 3
* 2-->1--->3
* */
public static ListNode swapPairs(ListNode head) {
if(head==null || head.next == null) return head;
ListNode next = head.next;
ListNode nextN = head.next.next;
head.next=null;
next.next=head;
head.next=swapPairs(nextN);
return next;
}
}