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

Credits:
Special thanks to @aadarshjajodia for adding this problem and creating all test cases.

Subscribe to see which companies asked this question


题意:


基本的意思就是对于一个链表,把位置是偶数的接在位置是奇数的位置后面,例如:


1-2-3-4-5-6


变化后:


1-3-5-2-4-6


解题分析:


这里我的思路就是利用分成两个链表,然后分别把位置为奇数的归一类,把位置为偶数的归为一类。

最后把位置为偶数的链表接在位置为奇数链表的后面。


class OddEvenLink{
	public:
		LinkNode* oddEvenList(ListNode* head)
		{
			if(!head)
					return head;
			ListNode* first = head
			ListNode* second = head->next;
			ListNode* temp = second;
			while(second && second->next)
			{
				first->next = second->next;
				first = first->next;
				second->next = first->next;
				second = second->next;
			}
			first->next = temp;
			return head;
		}
}

Odd Even Linked List(奇偶链表)_第1张图片




你可能感兴趣的:(Odd Even Linked List(奇偶链表))