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
.
双指针,odd和even,随后对odd.next和even.next进行更新,再循环里面应该先更新evenCur的next,如果直接更新偶数的结构,中间的node就被release掉了,同时evenCur.next一定赋值为null,也要判断奇数的最后一个node是不是为null
class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode evenDummy = new ListNode(0);
ListNode node = head;
ListNode evenCur = evenDummy;
ListNode prev = new ListNode(0);
while(node != null && node.next != null) {
prev = node;
evenCur.next = node.next;
evenCur = evenCur.next;
ListNode tmp = node.next.next;
node.next = tmp;
node = tmp;
}
evenCur.next = null;
if (node == null) {
prev.next = evenDummy.next;
}
else{
node.next = evenDummy.next;
}
return head;
}