문제 출처 : leetcode.com/problems/swap-nodes-in-pairs/
문제 해석 : 링크드 리스트의 페어의 값을 바꾸는 문제이다.
문제 풀이 : 링크드 리스트의 연결 상태를 변경하여 풀이할 수 있다. 다만 무한 루프에 빠지지 않게 주의해서 코드를 작성해야한다.
( 본 풀이는 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 사이트에 있습니다. 혹시 문제가 되는 부분이 있으면 연락 바랍니다.
'📊알고리즘, 문제풀이 > 📈문제풀이 (PS)' 카테고리의 다른 글
[알고리즘][Python] LeetCode 92 Reverse Linked List 2 문제 풀이 (0) | 2021.02.22 |
---|---|
[알고리즘][Python] LeetCode 328 Odd Even Linked List 문제 풀이 (0) | 2021.02.22 |
[알고리즘][Python] LeetCode 2 Add Two Numbers 문제 풀이 (0) | 2021.02.22 |
[알고리즘][Python] LeetCode 206 Reverse Linked List 문제 풀이 (0) | 2021.02.22 |
[알고리즘][Python] LeetCode 234 Palindrome Linked List 문제 풀이 (0) | 2021.02.21 |