http://blog.csdn.net/jiyanfeng1/article/details/8607889
Segregate even and odd nodes in a Linked List
给你一个单链表,修改此单链表,使得前面是偶数,后面是奇数。偶数间的相对顺序不变,奇数间的相对顺序不变。返回修改后的单链表的头节点。
例如:
Input: 17->15->8->12->10->5->4->1->7->6->NULL
Output: 8->12->10->4->6->17->15->5->1->7->NULL
Input: 8->12->10->5->4->1->6->NULL
Output: 8->12->10->4->6->5->1->NULL
// If all numbers are even then do not change the list
Input: 8->12->10->NULL
Output: 8->12->10->NULL
// If all numbers are odd then do not change the list
Input: 1->3->5->7->NULL
Output: 1->3->5->7->NULL
下面给出了两个函数,第一个函数segregate1可以保有奇偶数内部的相对顺序。第二个函数segregate2采用类似于“单链表的快速排序”的思路,代码简洁,但是不能保证奇数偶数内部的相对顺序。
代码如下:
- void segregate1(LNode **head_ref)
- {
- LNode *end = *head_ref;
-
- LNode *prev = NULL;
- LNode *curr = *head_ref;
-
-
- while(end->next != NULL)
- end = end->next;
-
- LNode *new_end = end;
-
-
-
- while(curr->data %2 != 0 && curr != end)
- {
- new_end->next = curr;
- curr = curr->next;
- new_end->next->next = NULL;
- new_end = new_end->next;
- }
-
-
-
- if (curr->data%2 == 0)
- {
-
- *head_ref = curr;
-
- while(curr != end)
- {
- if ( (curr->data)%2 == 0 )
- {
- prev = curr;
- curr = curr->next;
- }
- else
- {
-
- prev->next = curr->next;
-
- curr->next = NULL;
-
- new_end->next = curr;
-
- new_end = curr;
-
- curr = prev->next;
- }
- }
- }
-
-
-
- else
- prev = curr;
-
-
-
- if((end->data)%2 != 0)
- {
- prev->next = end->next;
- end->next = NULL;
- new_end->next = end;
- }
- return;
- }
-
- LNode* segregate2(LNode* head)
- {
-
-
-
- if(head){
- LNode* pslow = head;
- LNode* pfast = NULL;
-
-
-
- while(pslow && !(pslow->data & 1)){
- pslow = pslow->next;
- }
-
- if(pslow){
- pfast = pslow->next;
- while(pfast){
- if(!(pfast->data & 1)){
- swap(pfast->data, pslow->data);
- pslow = pslow->next;
- }
- pfast = pfast->next;
- }
- }
- }
- return head;
- }