题目类型:链表
题意:
给出一个链表,按对交换节点,
- 常数空间
- 不能用改变节点的值的方法做,需要交换节点本身。
我的思路:迭代。两两交换,修改next等指针
效率:10%
对于当前节点first,和下一个节点second
- 记录上一次交换后的最后一个节点pre
- 因为交换后链表断裂,所以暂存second下一个节点的位置,temp = second.next;
- pre.next = second; second.next = first; first.next = temp;
- 更新pre = first,继续交换下面的节点
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode pre = new ListNode(0);
ListNode copy = pre;
ListNode first = head;
ListNode second = head.next;
while (first != null && second != null) {
first.next = second.next;//相当于 暂存下一个的指针
pre.next = second;
second.next = first;
pre = first;
first = first.next;
second = (first != null) ? first.next : null;
}
return copy.next;
}
}
方法二:递归
效率略高于迭代
//方法二:递归
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;
}