Skip to content

Commit ae5f4d5

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 19.1 MB (94.05%)
1 parent acfac7b commit ae5f4d5

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
<p>Given the <code>head</code> of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return <em>the reordered list</em>.</p>
2+
3+
<p>The <strong>first</strong> node is considered <strong>odd</strong>, and the <strong>second</strong> node is <strong>even</strong>, and so on.</p>
4+
5+
<p>Note that the relative order inside both the even and odd groups should remain as it was in the input.</p>
6+
7+
<p>You must solve the problem&nbsp;in <code>O(1)</code>&nbsp;extra space complexity and <code>O(n)</code> time complexity.</p>
8+
9+
<p>&nbsp;</p>
10+
<p><strong class="example">Example 1:</strong></p>
11+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/10/oddeven-linked-list.jpg" style="width: 300px; height: 123px;" />
12+
<pre>
13+
<strong>Input:</strong> head = [1,2,3,4,5]
14+
<strong>Output:</strong> [1,3,5,2,4]
15+
</pre>
16+
17+
<p><strong class="example">Example 2:</strong></p>
18+
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/10/oddeven2-linked-list.jpg" style="width: 500px; height: 142px;" />
19+
<pre>
20+
<strong>Input:</strong> head = [2,1,3,5,6,4,7]
21+
<strong>Output:</strong> [2,3,6,7,1,5,4]
22+
</pre>
23+
24+
<p>&nbsp;</p>
25+
<p><strong>Constraints:</strong></p>
26+
27+
<ul>
28+
<li>The number of nodes in the linked list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
29+
<li><code>-10<sup>6</sup> &lt;= Node.val &lt;= 10<sup>6</sup></code></li>
30+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, val=0, next=None):
4+
# self.val = val
5+
# self.next = next
6+
class Solution:
7+
def oddEvenList(self, head: Optional[ListNode]) -> Optional[ListNode]:
8+
if head is None:
9+
return head
10+
odd = head
11+
even = total = head.next
12+
13+
while even and even.next:
14+
odd.next = even.next
15+
odd = odd.next
16+
even.next = odd.next
17+
even = even.next
18+
19+
odd.next = total
20+
return head

0 commit comments

Comments
 (0)