-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSolution.py
30 lines (22 loc) ยท 1.23 KB
/
Solution.py
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
28
29
30
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head: # edge case๊ฐ ์์ด์ ์์ฑ
return head
prev, even = head, head.next
while even and even.next: # ๋ง์ง๋ง ๋
ธ๋๊ฐ None ๊ฐ์ ๊ฐ์ง ๊ฒฝ์ฐ ํ์ถ or even ๋ค์ ๋
ธ๋๊ฐ ์กด์ฌํด์ผ ํจ.
odd = even.next # ๋๊น์ง ๋ค ๊ฐ์ ๊ฒฝ์ฐ์ even.next๊ฐ ์กด์ฌํ์ง ์์ผ๋ฏ๋ก ์์์ ์ ์ธํด์ค๋ค.
prev.next, odd.next, even.next = odd, prev.next, odd.next # ๊ฐ๊ฐ์ ๊ฐ์ ํ ๋ฒ์ ๋ค์คํ ๋น ํด์ค๋ค.
even, prev = even.next, prev.next # ๋ค์ ๊ฐ์ ํ ๋นํด์ค๋ค.
return head
solution: Solution = Solution()
solution.oddEvenList(
ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6, ListNode(7, ListNode(8)))))))))
solution: Solution = Solution()
solution.oddEvenList(ListNode(2, ListNode(1, ListNode(3, ListNode(5, ListNode(6, ListNode(4, ListNode(7, None))))))))
solution: Solution = Solution()
solution.oddEvenList(ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, None))))))