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
.
以先奇后偶的序列重排链表。
重新创建一个列表的话,很容易,但题目要求似乎是一次遍历,并且不能创建新的链表,也就是在原链表中调整节点位置。
所以解决思路是,把奇节点插入在奇节点后方,并在原链表中删除对应位置的节点。
class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head) return head; ListNode* p = head; ListNode* q = head->next; while (q && q->next) { ListNode* temp = q->next; //记录节点 q->next = q->next->next; //删除原节点位置 temp->next = p->next; //重组链表 p->next = temp; //插入节点 p = p->next; q = q->next; } return head; } };