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 …
s思路: 1. 這個簡單啊。由于是分成兩個鏈表后再連接起來,那么先找到兩個鏈表的頭,然后按照交叉的順序一步一步的分解成兩條鏈表,由于是很規(guī)則的操作,所以也沒啥幺蛾子。
class Solution {public: ListNode* oddEvenList(ListNode* head) { // if(!head) return NULL; ListNode* head1=head,*head2=head->next;//bug:看到head->next,就要自然反映這是在裸奔,沒有加保護的裸奔,所以要把保護加在前面! ListNode* odd=head1,*even=head2; while(even&&even->next){//注意: odd->next=even->next; odd=odd->next; if(odd){ even->next=odd->next; even=even->next; } } odd->next=head2; return head; }};新聞熱點
疑難解答