[LeeCode] 24. Swap Nodes in Pairs
                    
                2021. 1. 14. 22:12ㆍProblem Solving/LeetCode
Leetcode 24. 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
나의 풀이1
# 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: ListNode) -> ListNode:
        node = head
        while node and node.next:
            node.val, node.next.val = node.next.val, node.val
            node = node.next.next
        return head값 자체를 swap 해주는 것이다.
다른 풀이
파이썬 알고리즘 인터뷰 p.230의 반복 풀이를 풀어서 그림으로 그리면 이렇다.
복잡해서 이해하는데 엄청 오래걸렸다.. 반복해서 봐야할것 같다.

a -> b -> c -> d 라고 했을때,
1. a 가 c를 가리키게
2. b 가 a를 가리키게
3. prev, head 각각 두칸씩 이동하도록 설정.
4. root는 처음에 prev가 가리키던 head일 테니까 root.next 리턴
Study
Reference
- 파이썬 알고리즘 인터뷰
|  | 
 | 
반응형
    
    
    
  'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 20. Valid Parentheses (0) | 2021.01.18 | 
|---|---|
| [LeetCode] 328. Odd Even Linked List (0) | 2021.01.15 | 
| [LeetCode] 2. Add Two Numbers (0) | 2021.01.14 | 
| [LeetCode] 206. Reverse Linked List (0) | 2021.01.13 | 
| [LeetCode] 234. Palindrome Linked List (0) | 2021.01.12 |