Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.
Example 1:
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]
Example 2:
Input: head = [2,1,3,5,6,4,7]
Output: [2,3,6,7,1,5,4]
Constraints:
n == number of nodes in the linked list
0 <= n <= 104
-106 <= Node.val <= 106
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
current = head
while current and current.next:
val = current.next.val
current.next.val = current.val
current.val = val
current = current.next.next
return head
[실행 결과]
Runtime: 28 ms
Memory Usage: 14.4
[접근법]
첫번째 노드를 val 에 저장한다
첫번째 노드를 두번째 노드에 저장한다 current.next.val = current.val
val을 첫번째 자리에 넣는다.
해당 리스트의 앞 두자리를 없앤다.
head를 출력한다.
[느낀점]
이전 노드를 복사하기.... 여기서 또 실수했다.