Leetcode 1721. Swapping Nodes in a Linked List

2021-07-01 10:29:52 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

  • Version 1
代码语言:javascript复制
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
代码语言:javascript复制
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

  1. https://leetcode.com/problems/swapping-nodes-in-a-linked-list/

0 人点赞