一、问题描述
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:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->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 ...
二、问题分析
无。
三、算法代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode oddTail = head;
ListNode evenTail = head.next;
ListNode evenHead = evenTail;
while(oddTail.next != null && evenTail.next != null){
oddTail.next = evenTail.next;
oddTail = oddTail.next;
evenTail.next = oddTail.next;
evenTail = evenTail.next;
}
oddTail.next = evenHead;
return head;
}
}
链表奇偶节点重组
本文介绍了一种算法,该算法接收一个单链表作为输入,并将所有奇数位置的节点分组在一起,随后是所有偶数位置的节点。重点是在不使用额外的空间复杂度(O(1))的情况下实现这一目标,同时确保运行时间为O(nodes)。
3766

被折叠的 条评论
为什么被折叠?



