Leetcode 1721. Swapping Nodes in a Linked List
Posted SnailTyan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 1721. Swapping Nodes in a Linked List相关的知识,希望对你有一定的参考价值。
文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
class 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
class 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
以上是关于Leetcode 1721. Swapping Nodes in a Linked List的主要内容,如果未能解决你的问题,请参考以下文章
Codeforces 903E Swapping Characters
第15届浙江省赛 D Sequence Swapping(dp)
LeetCode Algorithm 1721. 交换链表中的节点