LeetCode 328. Odd Even Linked List
一开始理解错题意,以为是根据节点内的值是奇偶来分成不同group,实际上是节点所在位置的奇偶(位置从1开始算起)。
思路正确后仍然RE的代码:
1 class Solution { 2 public: 3 ListNode* oddEvenList(ListNode* head) { 4 if(head == NULL) return head; 5 if(head->next == NULL) return head; 6 7 ListNode* odd = head, * even = head->next; 8 odd->next = NULL; 9 even->next = NULL; 10 ListNode* o_head = odd, * e_head = even; 11 while(odd && even && even->next){ 12 odd->next = even->next; 13 odd = odd->next; 14 15 even->next = odd->next; 16 even = even->next; 17 } 18 even->next = NULL; 19 odd->next = e_head->next; 20 return o_head->next; 21 } 22 };
起因是8、9行,因为odd和even本身已经是head和head->next两个节点,再设置next为NULL就相当于截断了原链表,even->next=NULL,进不了while循环。如果把18、19注释掉,不会RE。
1 class Solution { 2 public: 3 ListNode* oddEvenList(ListNode* head) { 4 if(head == NULL) return head; 5 if(head->next == NULL) return head; 6 7 ListNode* odd = head, * even = head->next; 8 ListNode* o_head = odd, * e_head = even; 9 10 while(odd && even && even->next){ 11 odd->next = even->next; 12 odd = odd->next; 13 14 even->next = odd->next; 15 even = even->next; 16 } 17 // even->next = NULL;可有可无 18 odd->next = e_head; 19 return o_head; 20 } 21 };