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;
};