본문 바로가기

Algorithm/파이썬 알고리즘 인터뷰 스터디

[연결리스트] 17 페어의 노드 스왑(Swap Nodes in Pairs)

<LeetCode 문제>

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칸씩이동하며 값을 swap해주면 됩니다.

# 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]:
        cur=head
        
        while cur and cur.next: #next가 존재할때
            cur.val,cur.next.val = cur.next.val,cur.val #swap
            cur = cur.next.next #2칸 이동
            
        return head

<학습내용>

1.

<학습이 필요한 내용>