https://leetcode.com/problems/odd-even-linked-list/
Odd Even Linked List - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
풀이 과정
1 -> 2 -> 3 -> 4 -> 5 -> 6을 1 -> 3 -> 5 -> 2 -> 4 -> 6과 같이 홀수 번째 링크드 리스트 이후에 짝수 번째 링크드 리스트가 오게 하는 문제이다.
홀수번째 인덱스와 짝수번째 인덱스를 가리키는 변수를 반복문으로 바꿔가면서 문제를 해결하였다.
소스 코드
class Solution:
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
odd = head
even = head.next
even_head = head.next
while even and even.next:
odd.next, even.next = odd.next.next, even.next.next
odd, even = odd.next, even.next
odd.next = even_head
return head
'알고리즘 문제 풀이 > 리트코드' 카테고리의 다른 글
LeetCode - 316. Remove Duplicate Letters [Python] (0) | 2022.08.02 |
---|---|
LeetCode - 20. Valid Parentheses [Python] (0) | 2022.07.28 |
LeetCode - 24. Swap Nodes in Pairs [Python] (0) | 2022.07.27 |
LeetCode - 2. Add Two Numbers [Python] (0) | 2022.07.27 |
LeetCode - 206. Reverse Linked List [Python] (0) | 2022.07.27 |