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 ...
Credits:
Special thanks to @aadarshjajodia for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
思路:
0.初始状态
tmp prev cur
1 ---> 2 ---> 3 ---> 4 ---> 5 ---> NULL
1. prev->next = cur->next;
tmp prev cur
| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄↓
1 ---> 2 -x-> 3 ---> 4 ---> 5 ---> NULL
2.cur->next = tmp->next
tmp prev cur
| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄↓
1 ---> 2 3 -x-> 4 ---> 5 ---> NULL
↑____│
3.tmp->next = cur;
tmp prev cur
| ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄ ̄↓
1 -x-> 2 ---> 3 4 ---> 5 ---> NULL
│ ↑____│ ↑
│_____________│
4.操作完成后的链表
tmp cur prev
1 ---> 3 ---> 2 ---> 4 ---> 5 ---> NULL
5.指针后移
tmp = tmp->next;
prev = prev->next;
cru = prev->next;
tmp prev cur
1 ---> 3 ---> 2 ---> 4 ---> 5 ---> NULL
code:
/**
* 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) return head;
ListNode *tmp = head;
ListNode *prev = head->next;
if(!prev) return head;
ListNode *cur = prev->next;
while(prev && prev->next) {
cur = prev->next;
prev->next = cur->next;
cur->next = tmp->next;
tmp->next = cur;
tmp = tmp->next;
prev = prev->next;
}
return head;
}
};