您的位置:首页 > 其它

Leetcode:328. Odd Even Linked List

2016-07-26 23:44 281 查看
328. Odd Even Linked List QuestionEditorial Solution My Submissions

Total Accepted: 38481

Total Submissions: 96844

Difficulty: Medium

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

思路:使用两个头指针交替进行,最后将偶指针连接在奇指针后面。该方法效率较高,运算速度为16ms,击败96%提交。

class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(head==NULL ||head->next==NULL)
return head;
ListNode* oddhead=head;
ListNode* evenhead=head->next;
ListNode* sechead=head->next;
int i=1;
while(oddhead&&evenhead)
{
if(i%2==1)
{
if(evenhead->next)
{
oddhead->next=evenhead->next;
oddhead=oddhead->next;
}
else
evenhead=evenhead->next;
i++;
}
else
{
if(oddhead->next)
{
evenhead->next=oddhead->next;
evenhead=evenhead->next;
}
else
{
evenhead->next=NULL;
break;
}
i++;
}
}
oddhead->next=sechead;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: