【LeetCode】328. Odd Even Linked List 解题记录
问题描述
Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.
The first node is considered odd, and the second node is even, and so on.
Note that the relative order inside both the even and odd groups should remain as it was in the input.
You must solve the problem in O(1) extra space complexity and O(n) time complexity.
测试样例
1 | Input: head = [1,2,3,4,5] |
1 | Input: head = [2,1,3,5,6,4,7] |
说明
1 | n == number of nodes in the linked list |
解题
思路
分别构造奇数位链表和偶数位链表,步长均为 2
,构造完成后将偶数位链表附加到奇数位链表之后。
补充:
- 链表
- 时间复杂度
O(n)
代码
法一:
1 | /** |
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哆啦 C 梦!
评论