[알고리즘] leetcode swap node in pairs python

진실·2022년 11월 29일
0

알고리즘

목록 보기
22/22
post-custom-banner

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]:
        n = 0
        cur = head
        pre = None
        
        while cur: 
            first = cur
            
            if not cur.next : 
                break
            second = cur.next
            
            first.next = second.next
            second.next = first
            
            if pre : 
                pre.next = second
            else : 
                head = second
            
            pre = first
            
            if cur.next : 
                cur = cur.next
            else :
                cur = None
profile
반갑습니다.
post-custom-banner

0개의 댓글