파비의 매일매일 공부기록

2023.05.16 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.16 Today's Challenge

fabichoi 2023. 5. 16. 23:45

https://leetcode.com/problems/swap-nodes-in-pairs/

 

Swap Nodes in Pairs - LeetCode

Can you solve this real interview question? Swap Nodes in Pairs - Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be chan

leetcode.com

또다시 링크드 리스트 ㅋㅋㅋ

class Solution:
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head:
            return head
        
        prev, cur, ans = None, head, head.next
        
        while cur and cur.next:
            adj = cur.next

            if prev:
                prev.next = adj
            
            cur.next, adj.next = adj.next, cur
            prev, cur = cur, cur.next

        return ans or head
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.18 Today's Challenge  (0) 2023.05.18
2023.05.17 Today's Challenge  (0) 2023.05.17
2023.05.15 Today's Challenge  (1) 2023.05.15
2023.05.14 Today's Challenge  (0) 2023.05.14
2023.05.13 Today's Challenge  (1) 2023.05.13
Comments