작심삼일

[LeetCode] 24 | Swap Nodes in Pairs | Python 본문

스터디/코테

[LeetCode] 24 | Swap Nodes in Pairs | Python

yun_s 2022. 2. 16. 10:24
728x90
반응형

문제 링크: https://leetcode.com/problems/swap-nodes-in-pairs/


문제

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)


조건

  • The number of nodes in the list is in the range [0, 100].
  • 0 <= Node.val <= 100

내 풀이

(2n)번째와 (2n+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 swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head: return head
        a, b = head, head.next
        
        while b:
            temp = b.val
            b.val = a.val
            a.val = temp
            if not b.next or not b.next.next:
                return head
            a, b = a.next.next, b.next.next
        
        return head
728x90
반응형
Comments