原题描述
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:
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 …
分析
先记下第一个偶数节点的位置,从第一个节点开始对每个节点进行操作,使其后继节点变为原后继节点的后继节点,即node->next=node->next->next。然后将最后一个奇数节点指向第一个偶数节点。
代码示例
class Solution {
public:
ListNode* oddEvenList(ListNode* head)
{
if(head == NULL)
return head;
ListNode* second = head -> next;
ListNode* node = head;
ListNode* temp = NULL;
int count = 1;
while (node -> next != NULL)
{
temp = node;
node = node -> next;
temp -> next = temp -> next -> next;
count++;
}
if(count % 2 != 0)
node -> next = second;
else
{
temp -> next = second;
}
return head;
}
};