把链表中的奇偶数分开

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;
  
  /* Get pointer to the last node */
  while(end->next != NULL)
       end = end->next; 
  
  LNode *new_end = end;
  
  /* Consider all odd nodes before the first even node
     and move then after 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;
  }   
  
  // 10->8->17->17->15
  /* Do following steps only if there is any even node */
  if (curr->data%2 == 0)
  {
    /* Change the head pointer to point to first even node */
    *head_ref = curr;     
    /* now current points to the first even node */
    while(curr != end)
    {
      if ( (curr->data)%2 == 0 )
      {
         prev = curr;
         curr = curr->next;
      }
      else
      {
         /* break the link between prev and current */
         prev->next = curr->next; 
          /* Make next of curr as NULL  */
         curr->next = NULL;
         /* Move curr to end */
         new_end->next = curr;
         /* make curr as new end of list */
         new_end = curr;
         /* Update current pointer to next of the moved node */
         curr = prev->next;
      }
    }
  }
  
  /* We must have prev set before executing lines following this 
     statement */
  else  
    prev = curr;
  
  /* If the end of the original list is odd then move this node to
    end to maintain same order of odd numbers in modified list */
  if((end->data)%2 != 0)
  {
      prev->next = end->next;
      end->next = NULL;
      new_end->next = end;
  }
  return;
}

LNode* segregate2(LNode* head)
{// Note that this function cannot maintain the
 // relative order inside odd numbers and even numbers.
 // For example, 10->9->7->5->2->NULL becomes the following
 // 10->2->7->5->9->NULL.
	if(head){
		LNode* pslow = head;
		LNode* pfast = NULL;

		// find the 1st odd node in the linked list,
		// and save the pointer to node in pslow.
		while(pslow && !(pslow->data & 1)){
			pslow = pslow->next;
		}

		if(pslow){ // now pslow points to the 1st odd node.
			pfast = pslow->next;
			while(pfast){
				if(!(pfast->data & 1)){
					swap(pfast->data, pslow->data);
					pslow = pslow->next;
				}
				pfast = pfast->next;
			}
		}
	}
	return head;
}

你可能感兴趣的:(把链表中的奇偶数分开)