Add to List 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:
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 ...

 

 

class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
//
if(head==nullptr)return head;
if(head->next == nullptr)return head;
ListNode* H = head;
ListNode* start;
auto mark = start;
int count = 0;
start = H->next;
mark = start;
///注意点一,链表结构变化后不要认为此链表指针没有变化
///注意点二,null指针不能使用next H->next,一定要判断H是否位nullptr,包括H->next->next;
///注意点三,特殊例子与一般的例子的驱动,特例驱动写出if排除,一般代表性的例子写一般程序
while(H)
{
if(H->next==nullptr)break;
if(H->next->next==nullptr)break;
H->next = H->next->next;
H = H->next;
start->next = start->next->next;
start = start->next;
}
H->next = mark;
return head;
}
};

posted on 2017-10-31 13:25  flyingwaters  阅读(131)  评论(0编辑  收藏  举报

导航