본문 바로가기
Programming/LeetCode

[LeetCode] Swapping Nodes in a Linked List

by 데이터현 2022. 4. 4.

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

 

Swapping Nodes in a Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

문제 풀이 접근이 어려웠다.

왼쪽까지 움직이고 왼쪽부터 next가 null일 때까지 움직이면 right가 나오는 것을 캐치하면 풀 수 있는 문제

 

단순 val 바꿔주는 코드

class Solution:
    def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        left = right = head
        for _ in range(k-1):
            left = left.next
            
        null_checker = left
        while null_checker.next:
            right = right.next
            null_checker = null_checker.next
            
        left.val, right.val = right.val, left.val
        return head

 

실제 노드 자체를 변경하는 코드

# 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]:
        dummy = left_prev = right_prev = ListNode(next=head)
        left = right = head
        for _ in range(k-1):
            left_prev = left
            left = left.next
        
        null_checker = left
        while null_checker.next:
            null_checker = null_checker.next
            right_prev = right
            right = right.next
        if left == right:
            return head
        left_prev.next, right_prev.next = right, left
        left.next, right.next = right.next, left.next
        return dummy.next

 

댓글