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 ...
這道題可以用一個指針完成贬蛙,也可以用兩個指針完成,思想都是一樣的牵囤,就是遍歷鏈表爬骤,將鏈表中的元素一個一個的操作卤妒。
一個指針稍微麻煩一點:
var oddEvenList = function(head) {
if (!head||!head.next||!head.next.next)
return head;
var p = head;
var head2 = head.next;
var tamp;
while (p) {
if (p.next&&p.next.next&&p.next.next.next) {
tamp = p.next.next;
p.next.next = p.next.next.next;
p.next = tamp;
p=p.next;
continue;
}
if (p.next&&p.next.next&&!p.next.next.next) {
tamp = p.next;
p.next = p.next.next;
tamp.next = null;
p.next.next = head2;
return head;
}
if (p.next&&!p.next.next) {
p.next = head2;
return head;
}
}
};
兩個指針就方便多了:
var oddEvenList = function(head) {
if (!head||!head.next||!head.next.next)
return head;
var odd = head, even = head.next, evenHead = even;
while (even&& even.next) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
};