24. Swap Nodes in Pairs Python3

Yelim Kim·2021년 10월 1일
0

Python Algorithm Interview

목록 보기
17/36
post-thumbnail

Problem

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

Constraints:

The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100

My code

class Solution:
    def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head: 
            return head
        odd= head
        even = head.next
        even_h = even
        
        while even and even.next:
            odd.next = even.next 
            odd = odd.next
            even.next = odd.next 
            even =even.next
        
        odd.next = even_h
        return head

Review

[실행 결과]
Runtime: 36 ms, Memory Usage: 16.3 MB

[접근법]
홀수와 짝수를 각각 나눠담기 위해 while문을 이용
.next를 서로에게 전달하면서 인자를 건너뛰며 저장한다.
마지막으로 홀수 리스트에 짝수 리스트를 붙여 출력한다.

[느낀점]
연결 리스트를 복사하는 부분이 어려웠다.
간단한 코드로 구현할 수 있는 방법이 없는지 생각해볼 것.

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글