작심삼일

[LeetCode] 1721 | Swapping Nodes in an Linked List | Python 본문

스터디/코테

[LeetCode] 1721 | Swapping Nodes in an Linked List | Python

yun_s 2022. 4. 4. 10:15
728x90
반응형

문제 링크: https://leetcode.com/problems/swapping-nodes-in-a-linked-list/


문제

You are given the head of a linked list, and an integer k.

Return the head of the linked list after swapping the values of the $k^{th}$ node from the beginning and the $k^{th}$ node from the end (the list is 1-indexed).


조건

  • The number of nodes in the list is n.
  • 1 <= k <= n <= $10^5$
  • 0 <= Node.val <= 100

내 풀이

리스트의 길이(N)를 잰다.

k번째와 N-k+1번째의 val을 바꾼다.


코드

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        N = 1
        count, first, second = head, head, head
        
        while count.next:
            count = count.next
            N += 1
        
        k1 = min(k, N-k+1)
        k2 = N-k1+1
        
        while k2 > 1:
            if k1 > 1:
                first = first.next
                k1 -= 1
            second = second.next
            k2 -= 1
        
        temp = first.val
        first.val = second.val
        second.val = temp
        
        return head
728x90
반응형
Comments