题解 | 链表的奇偶重排
链表的奇偶重排
https://www.nowcoder.com/practice/02bf49ea45cd486daa031614f9bd6fc3
/*
* 既然要分奇偶重排,则我们可以选择先用两条链表分别收纳奇偶节点,然后将链表链接起来,就能得到答案。
*/
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) {
// write code here
ListNode pre1 = new ListNode(-1);
ListNode pre2 = new ListNode(-1);
ListNode h1 = pre1;
ListNode h2 = pre2;
int sum = 1;
while(head != null){
if(sum++ % 2 > 0){
h1.next = head;
h1 = h1.next;
}else{
h2.next = head;
h2 = h2.next;
}
head = head.next;
}
h2.next = null;
h1.next = pre2.next;
return pre1.next;
}
}

