首页 > 代码库 > Reorder List

Reorder List

开始用递归总是说超时,迫不得已改成这个了。

还是得注意细节

void reorderList(ListNode* head) {
if(head == NULL || head->next==NULL || head->next->next==NULL) return;
int i=1,j;
ListNode* p = head;
while(p->next) {
i++;
p = p->next;
}
j = i;
i = (i+1)/2;
ListNode* head2 = head;
for(int n=i; n>1; n--) {
head2 = head2->next;
}
ListNode* tail = head2;
head2 = head2->next;
tail->next = NULL;
p->next = head2;
head2 = head2->next;
p->next->next = NULL;
while(head2 != p) {
ListNode* now = head2;
head2 = head2->next;
now->next = p->next;
p->next = now;
}

p = head;
int n = j-i;
while(n--) {
ListNode* now = head2;
head2 = head2->next;
now->next = p->next;
p->next = now;
p = now->next;
}
head;
return;
}

Reorder List