跟随carl代码随想录刷题
所用代码为python
中等两两交换链表中的节点题目:给你一个链表,两两交换其中相邻的节点,并
返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
⭐️示例1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
⭐️示例 2:
输入:head = []
输出:[]
⭐️示例 3:
输入:head = [1]
输出:[1]
思路:
定义虚拟头节点dummyhead,初始化dummyhead.next = head,临时指针cur = dummyhead
终止条件:
cur.next = None时,循环结束。cur.next.next = None时,循环结束。cur位于虚拟头节点,所以cur.next = None,直接结束。cur位于虚拟头节点,所以cur.next.next = None,直接结束。while((cur.next != None) and (cur.next.next != None)):
while (cur.next.next != None),那么当cur.next = None时,cur.next.next会发生空指针异常。初始化:
temp = cur.next # 临时指针temp用于保存节点1的值temp1 = cur.next.next.next # temp1保存节点3的值cur.next = cur.next.next # 指向节点2cur.next.next = temp # 节点2指向节点1temp.next = temp1 # 节点1指向节点3cur = cur.next.next # cur往后移动2位,开始下一次交换return dummyhead.next
# 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]:
dummyhead = ListNode(next = head) # 定义虚拟头节点
cur = dummyhead
while(cur.next and cur.next.next):
temp = cur.next
temp1 = cur.next.next.next
cur.next = cur.next.next
cur.next.next = temp
temp.next = temp1
cur = cur.next.next
return dummyhead.next