leetcode 328. Odd Even Linked List #Medium
题意:给定一个有n个节点的单链表,调整节点位置,使原奇数位置节点在偶数位置节点之前,奇(偶)数节点之间相对位置不变,
Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
要求:空间复杂度O(1),时间复杂度O(n)
分析:从头到尾顺序遍历链表所有节点,第一个节点加入odd链表,第二个加入even链表,如此交错添加节点直到链表尾。代码:
/**
* 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 *r=head,*e=head->next,*h[2]={r,e},*c=e->next;
for(int i=0;c;c=c->next,i=1-i){
h[i]->next=c;
h[i]=c;
}
h[0]->next=e;
h[1]->next=NULL;
return r;
}