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
풀이 과정
링크드 리스트를 2개씩 짝지어서 순서를 바꾸라는 문제이다.
중첩 함수 change를 재귀 함수로 사용하여 문제를 해결하였다.
소스 코드
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
def change(prev, node):
prev.next, node.next = node.next, prev
if prev.next and prev.next.next:
temp = prev.next
prev.next = temp.next
change(temp, prev.next)
root = head
if head and head.next:
root = head.next
change(head, head.next)
return root
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 20. Valid Parentheses [Python] (0) | 2022.07.28 |
---|---|
LeetCode - 328. Odd Even Linked List [Python] (0) | 2022.07.28 |
LeetCode - 2. Add Two Numbers [Python] (0) | 2022.07.27 |
LeetCode - 206. Reverse Linked List [Python] (0) | 2022.07.27 |
LeetCode - 234. Palindrome Linked List [Python] (0) | 2022.07.23 |