[Algorithm] LeetCode #24 - Swap Nodes in Pairs


개요

LeetCode #24, 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.)

Example 1:

Input: head = [1,2,3,4] Output: [2,1,4,3]

Example 2:

Input: head = [] Output: []

Example 3:

Input: head = [1] Output: [1]

Constraints:

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

# 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: ListNode) -> ListNode:
        root = prev = ListNode(None)
        # prev는 head보다 앞
        prev.next = head
        
        while head and head.next:

            # 처음 b 정의를 head가 가리키는 것으로 했다가
            # b가 head를 가리키고 head는 b의 다음을 가리키는 것으로 바꿈
            
            b = head.next
            head.next = b.next
            b.next = head
            
            # head의 이전인 prev가 b를 가리키게 함
            
            prev.next = b
            
            # move
            head = head.next
            prev = prev.next.next
        return root.next






© 2021.03. by JacobJinwonLee

Powered by theorydb