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 ...
我的AC(4ms,最快一批):
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* oddEvenList(struct ListNode* head) {
if(!head || !head->next)
return head;
struct ListNode *oddList, *evenList, *evenHead;
oddList = head;
evenList = evenHead = head->next;
while(oddList->next && evenList->next){
oddList->next = oddList->next->next;
evenList->next = evenList->next->next;
oddList = oddList->next;
evenList = evenList->next;
}
oddList->next = evenHead;
return head;
}分析:
1、if(!head || !head->next)一定要加,其实if(!head)就够了,防[]
2、链表的循环里总忘记并没有“++”,需要自己加list = list->next;
本文介绍了一种在O(1)空间复杂度和O(nodes)时间复杂度内将单链表中的节点按奇偶顺序重新排列的方法。通过一个C语言实现的例子展示了如何保持原有顺序的同时完成节点的重组。

2060

被折叠的 条评论
为什么被折叠?



