파비의 매일매일 공부기록

2023.05.15 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.15 Today's Challenge

fabichoi 2023. 5. 15. 23:45

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

 

Swapping Nodes in a Linked List - LeetCode

Can you solve this real interview question? 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 kth node from the beginning and the kth node from t

leetcode.com

이제 DP는 끝나고 링크드 리스트 문제들이 나올 예정인가 보다

class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        l_node = head
        for i in range(1, k):
            l_node = l_node.next
        r_node = head
        cur_node = l_node

        while cur_node.next:
            cur_node = cur_node.next
            r_node = r_node.next
        
        l_node.val, r_node.val = r_node.val, l_node.val

        return head
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.17 Today's Challenge  (0) 2023.05.17
2023.05.16 Today's Challenge  (0) 2023.05.16
2023.05.14 Today's Challenge  (0) 2023.05.14
2023.05.13 Today's Challenge  (1) 2023.05.13
2023.05.12 Today's Challenge  (0) 2023.05.12
Comments