Skip to content

Commit 1a88fda

Browse files
committed
odd even linked list
1 parent 2489cfc commit 1a88fda

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

328.OddEvenLinkedList.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
"""
2+
328. Odd Even Linked List
3+
Medium
4+
Linked List
5+
---
6+
Given the head of a singly linked list, group all the nodes with
7+
odd indices together followed by the nodes with even indices, and return the reordered list.
8+
9+
The first node is considered odd, and the second node is even, and so on.
10+
11+
Note that the relative order inside both the even and odd groups should remain as it was in the input.
12+
13+
You must solve the problem in O(1) extra space complexity and O(n) time complexity.
14+
15+
Example 1:
16+
Input: head = [1,2,3,4,5]
17+
Output: [1,3,5,2,4]
18+
19+
Example 2:
20+
Input: head = [2,1,3,5,6,4,7]
21+
Output: [2,3,6,7,1,5,4]
22+
23+
Constraints:
24+
The number of nodes in the linked list is in the range [0, 104].
25+
-106 <= Node.val <= 106
26+
"""
27+
28+
29+
from typing import Optional
30+
31+
32+
# Definition for singly-linked list.
33+
class ListNode:
34+
def __init__(self, val=0, next=None):
35+
self.val = val
36+
self.next = next
37+
38+
39+
# O(n) time | O(1) space
40+
class Solution:
41+
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
42+
if head:
43+
odd = head
44+
even = even_head = head.next
45+
while even and even.next:
46+
odd.next = odd = even.next
47+
even.next = even = odd.next
48+
odd.next = even_head
49+
return head

0 commit comments

Comments
 (0)