题目描述:
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.
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 …
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
题目大意:给一个单向链表,使得所有奇数号(从1开始)节点连在一起,偶数号节点连在一起(相对位置不变)。
思路:维护两个指针,一个指向当前遍历到的奇数号节点,一个指向偶数号节点,每遇到一个新的奇/偶数号节点就让当前指向的节点指向新节点,再令这个奇/偶指针指向新节点。最后合并两个链表。
c++代码:
/**
* 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) {
ListNode* tempOdd = NULL;
ListNode* tempEven = NULL;
ListNode* mid = NULL;
auto cur = head;
int flag = 1;
while (cur)
{
if (flag % 2)
{
if (tempOdd)
{
tempOdd->next = cur;
}
tempOdd = cur;
}
else
{
if (tempEven)
{
tempEven->next = cur;
}
else
{
mid = cur;
}
tempEven = cur;
}
cur = cur->next;
flag = flag % 2 + 1;
}
if (tempOdd)
tempOdd->next = mid;
if (tempEven)
tempEven->next = NULL;
return head;
}
};