반응형
Problem
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given1->2->3->4
, you should return the list as2->1->4->3
.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Solution
•current 노드를 저장해뒀다가 다음 라운드에서 next 변경해줘야함.
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 | class Solution: def swapPairs(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None : return head LN = None CN = head while CN and CN.next : NN = CN.next if LN : LN.next = NN else : head = NN CN.next, NN.next = NN.next, CN LN = CN CN = CN.next return head | cs |
Source
반응형
'0 > algorithm' 카테고리의 다른 글
Find First and Last Position of Element in Sorted Array (in Python) (0) | 2019.01.22 |
---|---|
Next Permutation (in Python) (0) | 2019.01.21 |
Generate Parentheses (in Python) (0) | 2019.01.21 |
Valid Parentheses (in Python) (0) | 2019.01.21 |
Remove Node From End of List (in Python) (0) | 2019.01.21 |