给你链表的头节点 head 和一个整数 k 。
交换 链表正数第 k 个节点和倒数第 k 个节点的值后,返回链表的头节点(链表 从 1 开始索引)。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[1,4,3,2,5]
示例 2:
输入:head = [7,9,6,6,7,8,3,0,9,5], k = 5
输出:[7,9,6,6,8,7,3,0,9,5]
示例 3:
输入:head = [1], k = 1
输出:[1]
示例 4:
输入:head = [1,2], k = 1
输出:[2,1]
示例 5:
输入:head = [1,2,3], k = 2
输出:[1,2,3]
提示:
链表中节点的数目是 n
1 <= k <= n <= 105
0 <= Node.val <= 100
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, val=0, next=None): 4 # self.val = val 5 # self.next = next 6 class Solution: 7 def swapNodes(self, head: ListNode, k: int) -> ListNode: 8 tmp = head 9 lens = 0 10 while tmp: 11 lens += 1 12 tmp = tmp.next 13 #当k大于链表长度一半时,保证a1在b1前面 14 k = min(k,lens - k + 1) 15 dummy = ListNode() 16 dummy.next = head 17 slow = fast = dummy 18 for i in range(k-1): 19 fast = fast.next 20 #a1表示正数第k个节点的前一个节点,a2表示正数第k个节点的后一个节点 21 a1,a2 = fast,fast.next.next 22 while fast.next and fast.next.next: 23 slow = slow.next 24 fast = fast.next 25 #b1表示倒数第k个节点的前一个节点,b2表示倒数第k个节点的后一个节点 26 b1,b2 = slow,slow.next.next 27 if a2 == b1.next: 28 a1.next,b1.next = a2,b2 29 a1.next.next = b1 30 else: 31 a1.next,b1.next = b1.next,a1.next 32 a1.next.next,b1.next.next = a2,b2 33 return dummy.next