友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
328. Odd Even Linked List
使用双指针,将链表拆分成奇偶数两个链表,然后再拼接!确实是个很棒的方法!
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input:
Output:1->2->3->4->5->NULL
1->3->5->2->4->NULL
Example 2:
Input: 2
Output:->1->3->5->6->4->7->NULL
2->3->6->7->1->5->4->NULL
Note:
-
The relative order inside both the even and odd groups should remain as it was in the input.
-
The first node is considered odd, the second node even and so on …
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Odd Even Linked List.
*
* Memory Usage: 38 MB, less than 12.50% of Java online submissions for Odd Even Linked List.
*
* Copy from: https://leetcode.com/problems/odd-even-linked-list/solution/[Odd Even Linked List solution - LeetCode]
*/
public ListNode oddEvenList(ListNode head) {
if (Objects.isNull(head)) {
return null;
}
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (Objects.nonNull(even) && Objects.nonNull(even.next)) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}