import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode oddEvenList (ListNode head) {
if(head == null) return head;
ListNode fake_head1 = new ListNode(-1);
ListNode fake_head2 = new ListNode(-1);
ListNode pre1 = fake_head1,pre2 = fake_head2;
int count = 1;
for(ListNode cur = head;cur != null;cur = cur.next,count++){
if((count&1) == 0){
pre2.next = new ListNode(cur.val);
pre2 = pre2.next;
}else {
pre1.next = new ListNode(cur.val);
pre1 = pre1.next;
}
}
pre1.next = fake_head2.next;
return fake_head1.next;
}
}
/**
看错了题,以为交换值的奇偶节点!
// 可以认定为,将找到所有奇数节点,将节点插到前面!
ListNode fake_head = new ListNode(-1);
fake_head.next = head;
ListNode pre = fake_head,rush = head,rush_pre = fake_head;
while(rush != null){
while(rush != null && (rush.val&1) == 0) {
rush_pre = rush_pre.next;
rush = rush.next;
}
if(rush == null) break;
if(pre.next == rush){
rush = rush.next;
pre = pre.next;
rush_pre = rush_pre.next;
continue;
}
// 断开旧链
rush_pre.next = rush.next;
// 插入新链
rush.next = pre.next;
pre.next = rush;
// 继续向后探寻!
rush = rush_pre.next;
pre = pre.next;
}
return fake_head.next;
**/