-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path328.py
52 lines (42 loc) · 1.2 KB
/
328.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# My first Solution. looks bad
class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
prev = head
head = head.next
first = prev
second = head
count = 0
while head:
count += 1
if head.next:
prev.next = head.next
prev = head
head = head.next
else:
prev.next = None
break
if count % 2 == 1:
prev.next = second
else:
head.next = second
return first
# My second Solution
class Solution2:
def oddEvenList(self, head: ListNode) -> ListNode:
if not head:
return head
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