파이썬 알고리즘 인터뷰 문제 17번(리트코드 24번) Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/
# 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]:
def helper(one):
if not one or not one.next:
return one
three = one.next.next
one.next.next = one
two = one.next
one.next = helper(three)
return two
return helper(head)
# 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 or not head.next:
return head
dummy = ListNode(0)
dummy.next = head
prev, curr, nxt = dummy, head, head.next
while nxt:
prev.next, nxt.next, prev, curr = nxt, curr, curr, nxt.next
if curr:
nxt = curr.next
else:
prev.next = None
break
if curr: # odd case
prev.next = curr
return dummy.next
# 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, one: Optional[ListNode]) -> Optional[ListNode]:
if one and one.next:
two = one.next
one.next = self.swapPairs(two.next)
two.next = one
return two
return one
# 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]:
prev = ListNode(0)
prev.next = head
result = prev
while head and head.next:
curr = head.next
head.next = curr.next
curr.next = head
prev.next = curr
head = head.next
prev = prev.next.next
return result.next
책 풀이랑 비슷하게 풀긴 했지만, 가독성이나 디테일이 차이가 있다.
그래도 재귀 풀이를 책 안보고 풀었다!