题目详述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
解法一
迭代。时间复杂度O(n),空间复杂度O(1)
说明:
1.dummy节点:用来标记头结点,最终返回dummy.next
2.prevNode节点:用来缓存firstNode节点的前驱节点,防止链表丢失。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(-1);
ListNode prevNode = dummy;
while(head != null && head.next != null) {
ListNode firstNode = head;
ListNode secondNode = head.next;
//交换和移动prevNode至下一次交换节点的前驱
firstNode.next = secondNode.next;
secondNode.next = firstNode;
prevNode.next = secondNode;
prevNode = firstNode;
//每次循环跳两个
head = firstNode.next;
}
return dummy.next;
}
}
解法二
递归。时间复杂度O(n),空间复杂度O(n)
class Solution {
public ListNode swapPairs(ListNode head) {
if(head ==null || head.next == null) return head;
ListNode firstNode = head;
ListNode secondNode = head.next;
//交换
firstNode.next = swapPairs(secondNode.next);
secondNode.next = firstNode;
return secondNode;
}
}