case status# EB23 - 劳工卡
a*0
1 楼
不递归无非就是分成两半 后一办reverse 然后插入到第一份去 我懒得写这么多代码
于是用了递归方法 结果超时 在自己电脑上跑了几个小case 都过了 不知道大家什么看
法 又超时了!
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null)
return;
if(head.next ==null)
return;
if(head.next.next == null)
return;
ListNode scanner = head;
int length =0;
while(scanner != null){
length++;
scanner = scanner.next;
}
head = reorderHelper(head, length);
}
public ListNode reorderHelper(ListNode start, int range){
ListNode scanner =start;
ListNode last = start;
int count = range-2;
if(range ==0)
return null;
if(range ==1)
return start;
while(count >0){
count--;
scanner = scanner.next;
}
last = scanner.next;
scanner.next = null;
ListNode temp = reorderHelper(start.next, range -2);
start.next = last;
last.next = temp;
return start;
}
}
于是用了递归方法 结果超时 在自己电脑上跑了几个小case 都过了 不知道大家什么看
法 又超时了!
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null)
return;
if(head.next ==null)
return;
if(head.next.next == null)
return;
ListNode scanner = head;
int length =0;
while(scanner != null){
length++;
scanner = scanner.next;
}
head = reorderHelper(head, length);
}
public ListNode reorderHelper(ListNode start, int range){
ListNode scanner =start;
ListNode last = start;
int count = range-2;
if(range ==0)
return null;
if(range ==1)
return start;
while(count >0){
count--;
scanner = scanner.next;
}
last = scanner.next;
scanner.next = null;
ListNode temp = reorderHelper(start.next, range -2);
start.next = last;
last.next = temp;
return start;
}
}