Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
做这个题,想到递归去实现题意。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
// 记录 head的下一个结点
ListNode temp = head.next;
// 递归 两两 交换后续结点
ListNode res = swapPairs(temp.next);
// 如果返回值不为空 那么应该将当前链表的后续引索更正
if( res != null ) temp.next = res;
// 头结点指向 当前结点后续的第二个结点,为temp 让出 老大结点做准备
head.next = temp.next;
// temp的下一个结点 指向 头结点 。自己要做老大了
temp.next = head;
// 把老大之位归还给 head
head = temp;
return head;
}
}
运行结果: