328. Odd Even Linked List
问题描述:
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 1:
Input:1->2->3->4->5->NULL
Output:1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output:2->3->6->7->1->5->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 ...
解题思路:
这道题让我们把奇数位的节点连到一起,把偶数位的节点连到一起。
所以我们可以用两个指针分别记录奇数位的起始(oddStart)和偶数位(evenStart)的起始。
然后遍历分别给偶数位和奇数位分别链接新的节点。
需要注意的是:
if(temp->next) temp->next = temp->next->next;
这里的判断条件,若出错会出现死循环!!!(因为最后的节点没有连到NULL)
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* oddEvenList(ListNode* head) { if(!head || !head->next) return head; ListNode* oddStart = head; ListNode* evenStart = head->next; ListNode* cur = oddStart; ListNode* prev = cur; while(cur && cur->next){ ListNode* temp = cur->next; cur->next = temp->next; if(temp->next) temp->next = temp->next->next; prev = cur; cur = cur->next; } if(cur){ cur->next = evenStart; }else{ prev->next = evenStart; } return head; } };