Problem: 24. 两两交换链表中的节点
文章目录
思路 & 解题方法
假如要交换1号节点和2号节点:
0->1->2->3变成
0->2->1->3就行了。
复杂度
时间复杂度:
O ( n ) O(n) O(n)
空间复杂度:
O ( 1 ) O(1) O(1)
Code
python
# 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]:
node0 = ans = ListNode(0, head)
node1 = head
while node1 and node1.next:
node2 = node1.next
node3 = node2.next
# 0->1->2->3
node0.next = node2
node2.next = node1
node1.next = node3
# 0->2->1->3
node0 = node1
node1 = node3
return ans.next