一、题目描述
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 ...
题目解读:给一个链表,将位于奇数位置的节点放在前面,偶数位置的节点放在后面。要求时间复杂度为o(n),空间复杂度为o(1)
思路:设置两个指针,一个用来串位于奇数位置的节点,一个用来串位于偶数位置的节点,最后再把两个链表连接起来。
c++代码(20ms,19.63%)
/**
* 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) {
if(head == NULL || head->next==NULL || head->next->next==NULL)
return head;
ListNode* odd = head;
ListNode* even = head->next;
ListNode* tmp = even;
while(odd != NULL && even != NULL && even->next != NULL){
odd->next=even->next;
odd = even->next;
even->next = odd->next;
even=odd->next;
}//while
if(odd!=NULL){
odd->next=tmp;
}//if
return head;
}
};