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 ...
要注意24行 要把ri->next變成NULL
不然無限迴圈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* oddEvenList(struct ListNode* head) { if(head==NULL)return NULL; struct ListNode* righthead=head->next; struct ListNode* lefthead = head; struct ListNode* le=head; struct ListNode* ri=head->next; while(le->next!=NULL && ri->next!=NULL){ if(ri->next!=NULL){ le->next=ri->next; le=ri->next; } if(le->next!=NULL){ ri->next=le->next; ri=le->next; }else{ ri->next=NULL; } } //printf("aa"); le->next=righthead; return head; } |
沒有留言:
張貼留言