题目
思路与算法
- 我们以给的例子1→2→3→4说明,因为只需要两两交换,因此最后得到2→1→4→3。
- 我们把过程写一下:1→2→3→4 到 2→1→3→4 到 2→1→4→3。先把1指到后面剩余的链表:1→3→4,再把2指到1: 2→1→3→4,每次重复这两个过程就可以了。具体的写法见代码。
代码实现
/**
* 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 first = head;
ListNode second = head.next;
first.next = swapPairs(second.next);
second.next = first;
// 返回头结点
return second;
}
}
复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(N) | O(N) |