본문으로 바로가기

LeetCode 24.Swap Nodes in Pairs

이 문제는 주어진 조건대로 

링크드 리스트이 인접한 노드들을 서로 교환한 다음

리스트의 head를 반환할 수 있도록 프로그램을 짜야한다.

leetcode에서 푼 문제 보기

leetcode에서 문제 보기

github에서 코드 보기

문제 조건

다음과 같이 주어진 링크드 리스트를 2개씩 나눠, 서로의 자리를 교환해야 한다.

Given 1->2->3->4, you should return the list as 2->1->4->3.

문제 풀이

순회를 시작하면서 이전노드와 다음 노드의 주소를 저장해두고, 순서에 맞게 차례대로 노드의 순서를 변경해야만 한다.

문제를 풀때의 팁은, 미리 linked list의 data를 head부터 순서대로 출력해주는 헬퍼 함수를 만들어두며 테스트를 하면서 순서를 바꾸는 것이다.

문제를 더 빨리 풀고 싶다면 꼭! head부터 시작하는 currentNode가 None이 아닐때까지 모든 원소들을 출력해주는 헬퍼 함수를 먼저 만들고 시작하자.

파이썬 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
 
class ListNode:
    def __init__(self, x, nextNode):
        self.val = x
        self.next = nextNode
 
 
class Solution:
    def swapPairs(self, currentNode):
        head = currentNode.next
 
        prevNode = None
        while currentNode != None:
            nextNode = currentNode.next
            if prevNode != None:
                prevNode.next = currentNode.next
            currentNode.next = nextNode.next
            nextNode.next = currentNode
 
            prevNode = currentNode
            currentNode = currentNode.next
 
        return head
 
 
if __name__ == "__main__":
    node4 = ListNode(4, None)
    node3= ListNode(3, node4)
    node2 = ListNode(2, node3)
    node1 = ListNode(1, node2)
 
    solution = Solution()
    newHead = solution.swapPairs(node1)
    while newHead != None:
        print(newHead.val)
        newHead = newHead.next
 
cs

#LeetCode 24. Swap Nodes in Pairs #LeetCode 24. Swap Nodes in Pairs 파이썬 #LeetCode 24. Swap Nodes in Pairs python