题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
思路一 递归
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next); //指向下一个子链表
next.next = head;
return next;
}
}
复杂度分析
时间复杂度:O(N),其中 N 指的是链表的节点数量。
空间复杂度:O(N),递归过程使用的堆栈空间。
思路二 迭代
class Solution {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode pre = new ListNode(-1); //哨兵,用来返回最后结果的头结点
pre.next = head;
ListNode temp = pre; //变量,记录指向 下一个交换位置相邻节点 的结点
while (temp.next != null && temp.next.next != null) {
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
}
复杂度分析
时间复杂度:O(N),其中 N 指的是链表的节点数量。
空间复杂度:O(1)