链表的奇偶重排
链表的奇偶重排
http://www.nowcoder.com/questionTerminal/02bf49ea45cd486daa031614f9bd6fc3
这道题奇偶链表,想不超时,循环中不能有运算操作。
这边采用分离链表的思路,定义四个指针,分别指向 奇数链表 头尾 偶数链表 头尾
最后拼接即可
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param head ListNode类
* @return ListNode类
*/
public ListNode oddEvenList (ListNode head) {
// write code here
//奇数链表头尾
ListNode head1=head;
ListNode tail1=head;
//偶数链表头尾
ListNode head2=head.next;
ListNode tail2=head.next;
if(head.next==null){
return head1;
}
ListNode index=head.next.next;
if(head.next==null){
return head1;
}
while(tail2.next!=null&&tail2.next.next!=null){
tail1.next=tail2.next;
tail2.next=tail2.next.next;
tail2=tail2.next;
tail1=tail1.next;
}
if(tail2.next!=null){
tail1.next=tail2.next;
tail1=tail1.next;
tail2.next=null;
}
tail1.next=head2;
return head1;
}
}
查看16道真题和解析