Leetcode 1721. Swapping Nodes in a Linked List | | Leetcode 1721. Swapping Nodes in a Linked List 文章作者:Tyan博客:noahsnail.com | CSDN | 简书 1. Description 2. Solution Version 1 1234567891011121314151617181920class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: length = 0 ptr = head while ptr: length += 1 ptr = ptr.next ptr = head count = 0 while ptr: count += 1 if count == k: beginning = ptr if count == length - k + 1 end = ptr ptr = ptr.next beginning.val, end.val = end.val, beginning.val return head Version 2 12345678910111213class Solution: def swapNodes(self, head: ListNode, k: int) -> ListNode: ptr = head for _ in range(1, k): ptr = ptr.next beginning = ptr end = head while ptr.next: ptr = ptr.next end = end.next beginning.val, end.val = end.val, beginning.val return head Reference https://leetcode.com/problems/swapping-nodes-in-a-linked-list/ 如果有收获,可以请我喝杯咖啡! 赏 微信打赏 支付宝打赏