题
这题似乎过于简单,官方都不屑于给出题解。。。
我的模拟思路
在链表头部搞个哑结点,然后利用两个间隔为2的指针,模拟一下完事儿。
/**
* 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;
// 先在原始链表的头部添加一个哑结点压压惊
ListNode dummyNode = new ListNode(0);
dummyNode.next = head;
// 直接模拟,借助双指针,两个指针间隔2个单位
ListNode pre = dummyNode;
ListNode next = dummyNode.next.next;
while(true) {
pre.next.next = next.next;
next.next = pre.next;
pre.next = next;
next = next.next;
if (next.next != null && next.next.next != null) {
pre = next;
next = next.next.next;
}
else {
break;
}
}
return dummyNode.next;
}
}
这里尤其注意:next指针在两个节点位置交换后的位置。
要么就用递归搞搞
注意递归的边界处理
/**
* 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;
} else {
// 否则处理一下当前的两个结点,定义两个指针
ListNode pre = head;
ListNode next = head.next;
// 递归进去
pre.next = swapPairs(next.next);
next.next = pre;
return next;
}
}
}