Odd Even LinkList

2016-03-13  本文已影响0人  aemaeth

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.

/**
* 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; }

上一篇 下一篇

猜你喜欢

热点阅读