思路:递归 和 非递归。
递归:
- 递归函数返回的是已经交换过的节点;
- 递归函数内部需要实现两个节点的交换
非递归:遍历链表实现交换即可。
代码,递归:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode temp = head.next;
head.next = swapPairs(head.next.next);
temp.next = head;
return temp;
}
}
代码:非递归
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode fake = new ListNode(0, head);
ListNode pre = fake;
while (head != null && head.next != null) {
pre.next = head.next;
head.next = head.next.next;
pre.next.next = head;
pre = pre.next.next;
head = pre.next;
}
return fake.next;
}
}