问题描述:
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.
思路:
很直接的想法,交替取节点加入到两个list中即可,然后odd list 尾部接even list头部即可。用一个evenTurn的标志来记录当前节点应该加入到odd list 还是even list,然后在遍历完后,注意将两个list的尾节点都置为NULL再衔接起来。
代码:
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
ListNode* oddHead;
ListNode* evenHead;
oddHead = head;
if (oddHead == NULL) return oddHead;
evenHead = head->next;
if (evenHead == NULL) return oddHead;
ListNode* oddNow = oddHead;
ListNode* evenNow = evenHead;
ListNode* now = evenNow->next;
bool evenTurn = false; //next is the third one
while (now != NULL)
{
if (evenTurn)
{
evenNow->next = now; //link to even list
evenNow = evenNow->next;
now = now->next;
evenTurn = false;
}
else
{
oddNow->next = now; //link to odd list
oddNow = oddNow->next;
now = now->next;
evenTurn = true;
}
}
//这里如果不处理好odd list 和 even list 的末节点的next,很容易造成死循环
evenNow->next = NULL;
oddNow->next = NULL;
oddNow->next = evenHead; //joint them
return oddHead;
}
};