LeetCode-24. 两两交换链表中的节点【递归 链表】
题目描述:
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
解题思路一:双指针1
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head: return head
dummy_head = ListNode(next=head)
pre = dummy_head
cur = dummy_head.next
while cur.next:
temp = cur.next
pre.next = temp
cur.next = temp.next
temp.next = cur
if cur.next == None:
break
pre = cur
cur = cur.next
return dummy_head.next
时间复杂度:O(n)
空间复杂度:O(1)
解题思路二:双指针2
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head == None or head.next == None: return head
dummyHead = ListNode()
dummyHead.next = head
cur = dummyHead
while cur.next != None and cur.next.next != None:
tmp = cur.next
tmp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = tmp
cur.next.next.next = tmp1
cur = cur.next.next # 每次前进两个,并且判断后面有两个元素就交换
return dummyHead.next
时间复杂度:O(n)
空间复杂度:O(1)
解题思路三:递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
if head is None or head.next is None: return head
pre = head
cur = head.next
next = head.next.next
cur.next = pre
pre.next = self.swapPairs(next)
return cur
时间复杂度:O(n)
空间复杂度:O(n)