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]
Explanation:
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
Example 4:
Input: head = [1,2,3]
Output: [2,1,3]
Constraints:
[0, 100]
.0 <= Node.val <= 100
주어진 연결 리스트에서 인접한 두 노드마다 위치를 교환하고, 변경된 연결 리스트를 반환하는 문제입니다.
인접한 두 노드마다 서로의 next 노드를 변경하면 될 것으로 보입니다. 입출력을 보도록 하겠습니다.
연결 리스트가 있을 때, 현재 노드와 현재 노드의 다음 노드를 계속 교환해가면서 진행하기 때문에, 반복문과 재귀 방법을 사용할 수 있습니다. 방법이 바로 떠올랐네요!
바로 코드 설계를 진행해보도록 하겠습니다.
이 문제를 해결하기 위해, 반복문과 재귀를 사용한 두 가지 접근 방식을 설계합니다.
반복문 설계
prev
포인터를 더미 노드로 초기화합니다.first
)와 그 다음 노드(second
)를 찾습니다.prev
의 next
를 second
로 설정하여 두 노드의 위치를 변경합니다.first.next
와 second.next
를 적절히 설정하여 연결을 유지합니다.prev
를 한 쌍의 마지막 노드(first
)로 이동시켜 다음 쌍을 처리합니다.next
를 반환합니다.재귀 설계
first
)와 다음 노드(second
)를 식별합니다.first.next
를 재귀 호출을 통해 반환된 다음 결과로 설정합니다.second.next
를 first
로 설정하여 두 노드의 위치를 변경합니다.second
를 반환하여, 재귀 호출의 상위 호출에서 사용할 수 있도록 합니다.반복
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
# 2. iterative
def swapPairs(self, head):
# https://leetcode.com/problems/swap-nodes-in-pairs/submissions/1470789178
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
dummy = ListNode(next=head)
prev = dummy
while prev.next and prev.next.next:
first = prev.next
second = prev.next.next
prev.next = second
first.next = second.next
second.next = first
prev = first
return dummy.next
head
가 교환되는 경우를 포함한 모든 상황을 간단히 처리합니다.prev
포인터를 갱신하여 다음 쌍을 처리합니다.재귀
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
# # 1. recursion
def swapPairs(self, head):
# https://leetcode.com/problems/swap-nodes-in-pairs/submissions/1470802663
"""
:type head: Optional[ListNode]
:rtype: Optional[ListNode]
"""
if not head or not head.next:
return head
first = head
second = head.next
first.next = self.swapPairs(second.next)
second.next = first
return second
first
와 second
를 식별하고 위치를 변경한 뒤, 다음 노드로 재귀 호출을 진행합니다.second
를 결과로 사용합니다.이번 문제는 연결 리스트의 노드 교환 문제로, 반복(iterative)과 재귀(recursive) 방식을 모두 사용해 해결할 수 있었습니다.
head
가 변경될 수 있는 상황을 간단히 처리하는 방법을 배웠습니다.전체 코드는 다음 링크에서 확인할 수 있습니다.
읽어주셔서 감사합니다.