https://leetcode.com/problems/swap-nodes-in-pairs/
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
연결 리스트를 입력받아 페어 단위로 스왑하라
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Input: head = [1]
Output: [1]
재귀를 이용해서 리스트 노드 2개씩 보면서 두 개를 바꾸어주었다.
class Solution:
def swap(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head or not head.next:
return head
first, second = head, head.next
first.next, second.next = second.next, first
first.next = self.swap(first.next)
return second
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
return self.swap(head)
이번에는 책 풀이랑 비슷하게 풀어 깔끔하게 잘 푼것 같다.