File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ # Definition for singly-linked list.
2+ class ListNode :
3+ def __init__ (self , val = 0 , next = None ):
4+ self .val = val
5+ self .next = next
6+
7+ class Solution :
8+ def swapPairs (self , head : ListNode ) -> ListNode :
9+ cur = head
10+ # 처음에는 result = []에 append하는 식으로 했는데 직접 조작
11+ while cur and cur .next :
12+ cur .val , cur .next .val = cur .next .val , cur .val
13+ cur = cur .next .next
14+ return head
15+
16+ # 상길북 풀이 2
17+ # 반복구조
18+ def swapPairs (self , head : ListNode ) -> ListNode :
19+ root = prev = ListNode (None )
20+ prev .next = head
21+ while head and head .next :
22+ # 뒤에 값 넣기
23+ b = head .next # b = 2 head = 1
24+ # 다음값 미리 지정
25+ head .next = b .next # head.next = 3
26+ # 다음값을 1로 바꾸어 놓기
27+ b .next = head # 2.next = 1
28+
29+ prev .next = b # 이전 값은 2
30+
31+ # 다음 두 비교를 위해서...
32+ head = head .next
33+ prev = prev .next .next
34+
35+ return root .next
36+
37+ # 상길북 풀이 2
38+ # 재귀 구조
39+ def swapPairs (self , head : ListNode ) -> ListNode :
40+ if head and head .next :
41+ p = head .next
42+ # 스왑된 값 리턴 받음
43+ head .next = self .swapPairs (p .next )
44+ p .next = head
45+ return p
46+ return head
47+ # 다른 연결 리스트 문제들의 풀이와 마찬가지로, 실제로는 백트래킹 되면서 연결 리스트가 이어지게 된다.
48+
49+ # swapPairs(1) -> swapPairs(3)
50+ # 2 1 4 3
You can’t perform that action at this time.
0 commit comments