Problem
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: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 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 ...
class Solution { public ListNode oddEvenList(ListNode head) { if (head == null) return head; ListNode odd = head, even = head.next, evenHead = even; while (even != null && even.next != null) { odd.next = odd.next.next; even.next = even.next.next; odd = odd.next; even = even.next; } odd.next = evenHead; return head; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/73017.html
摘要:最后将奇数链表尾连到偶数链表头即可。改进的思路在于减少额外的变量创建。奇数指针的初始值为,而偶数指针的初始值为。则下一个奇数值位于上,此时将该奇数指针移动到上之后,偶数指针的值则为。 题目要求 Given a singly linked list, group all odd nodes together followed by the even nodes. Please note...
摘要:给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。需要记录偶数位节点的第一个节点,因为这是偶数链表的头节点,最后拼接链表时要用奇数链表的尾节点连接该节点。 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成...
摘要:给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。需要记录偶数位节点的第一个节点,因为这是偶数链表的头节点,最后拼接链表时要用奇数链表的尾节点连接该节点。 给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。 请尝试使用原地算法完成...
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 notthe value in the nodes.You should try to do it in plac...
Problem 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. Example Example:Given...
阅读 1748·2023-04-25 16:28
阅读 684·2021-11-23 09:51
阅读 1467·2019-08-30 15:54
阅读 1148·2019-08-30 15:53
阅读 2816·2019-08-30 15:53
阅读 3412·2019-08-30 15:43
阅读 3249·2019-08-30 11:18
阅读 3261·2019-08-26 10:25