📊알고리즘, 문제풀이/📈문제풀이 (PS)

[알고리즘][Python] LeetCode 24 Swap Nodes in Pairs 문제 풀이

Written by Donghak Park

문제 출처 : 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


문제 해석 : 링크드 리스트의 페어의 값을 바꾸는 문제이다.

 

문제 풀이 : 링크드 리스트의 연결 상태를 변경하여 풀이할 수 있다. 다만 무한 루프에 빠지지 않게 주의해서 코드를 작성해야한다.

( 본 풀이는 Python Algorithm Interview 책의 풀이를 참고했습니다. )


풀이 코드

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:

        root = front = ListNode(None)
        front.next = head
        while head and head.next:
            temp = head.next
            head.next = temp.next #두개 뒤
            temp.next = head

            front.next = temp
            head = head.next
            front = front.next.next

        return root.next

if __name__=="__main__":
    solution = Solution()
    head = ListNode(1,ListNode(2, ListNode(3, ListNode(4, None))))
    ret = solution.swapPairs(head)
    now = ret
    while now is not None:
        print(now.val, end = " ")
        now = now.next

author : donghak park
contact : donghark03@naver.com

## 문제의 저작권은 LeetCode 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.