Programming/LeetCode
[LeetCode] Swap Nodes in Pairs
데이터현
2022. 3. 24. 18:37
https://leetcode.com/problems/swap-nodes-in-pairs/
Swap Nodes in Pairs - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
짝을 이뤄서 노드를 변경하는 것 value 값을 변경하면 안된다.
1 <-> 2 까지는 괜찮은데
3 <-> 4 를 변경할때 1의 next가 3이 아닌 4가 되어야 해서 이 부분에서 신경을 써줘야 함.
반복문을 이용한 풀이
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
root = prev = ListNode(None)
prev.next = head
while head and head.next:
b = head.next
head.next = b.next
b.next = head
prev.next = b
head = head.next
prev = prev.next.next
return root.next
재귀를 이용한 풀이
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
while head and head.next:
p = head.next
head.next = self.swapPairs(p.next)
p.next = head
return p
return head