leetcode 328. Odd Even Linked List

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 ...



struct ListNode* oddEvenList(struct ListNode* head) {
	if (head == NULL)
		return NULL;
	struct ListNode*n, *n1, *pre,*head1;
	n = head; n1 = NULL; pre = NULL; head1 = NULL;
	int k = 1;
	while (n != NULL)
	{
		if (k % 2 == 0)
		{
			if (n1 == NULL)
			{
				n1 = n;
				head1 = n;
			}
			else
			{
				n1->next = n;
				n1 = n1->next;
			}
			pre->next = n->next;
			n = n->next;
		}
		else
		{
			pre = n;
			n = n->next;
		}
		k++;
	}
	if (n1 != NULL)
		n1->next = NULL;
	pre->next = head1;
	return head;
}

accepted


你可能感兴趣的:(LeetCode)