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 ...
1.如果节点个数大于等于三个才能进行相应的操作。如果不满足该条件,直接返回头指针。
2.指针p指向当前奇数节点的最后一个,q指向奇数节点链接的下一个节点。如上链表,p指向1的节点,q指向3。并且q需要一个前驱指针front,用来链接偶数节点。
3. 当1->3后,此时链表为1->3->2->4->5->NULL。由于下次p需要指向3节点,q需要指向5节点,因此在链接之前,先标记下一次q的前驱flag = q -> next,flag的下一个节点为下一次需要链接的奇数节点。此时flag指向4的节点。在链接完成后,p = q, front = flag, q = front -> next。
注:当链表为1->2->3->NULL时,当完成奇数节点链接后,由于flag == NULL,再无奇数节点可以链接。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (head == NULL || head -> next == NULL || head -> next -> next == NULL) {
return head;
}
ListNode* p = head, *q = head -> next -> next;
ListNode* front = head -> next;
ListNode* flag = NULL;
while (q) {
flag = q -> next;
front -> next = q -> next;
q -> next = p -> next;
p -> next = q;
if (flag == NULL) {
return head;
}
p = q;
front = flag;
q = flag -> next;
}
return head;
}
};