美文网首页
Odd Even LinkList

Odd Even LinkList

作者: aemaeth | 来源:发表于2016-03-13 00:08 被阅读0次

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:Given1->2->3->4->5->NULL ,return1->3->5->2->4->NULL

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* oddEvenList(struct ListNode* head) { struct ListNode *even; struct ListNode *even_head; struct ListNode *odd; //tailor=(struct ListNode*)malloc(sizeof(struct ListNode)); if(head==NULL||head->next==NULL) return head; even_head=head->next; odd=head; even=head->next; while(even!=NULL&&even->next!=NULL){ odd->next=odd->next->next; even->next=even->next->next; odd=odd->next; even=even->next; } odd->next=even_head; return head; }

相关文章