Reorder List

来源:互联网 发布:网站源码cmzy168 编辑:程序博客网 时间:2024/05/16 10:20

Given a singly linked list LL0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-2→…

You must do this in-place without altering the nodes' values.

For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.


算法:

1、找到中间结点,需要考虑奇偶性

2、将后一半链表反序

3、将两个链表按照要求合并


code:

class Solution {
public:
int lenList(ListNode* head){
ListNode* p =head;
int count = 0;
while(p!=NULL){
count++;
p = p->next;
}
return count;
}
void reorderList(ListNode* head) {

ListNode* reHead ;
int length = lenList(head);
if(length <2)
return;
int mid = length/2;
ListNode *first = head;
for (int i = 0; i < mid - 1 ; ++i) {
if(first->next!=NULL)
first = first->next;
}

ListNode *p = first->next;
first->next = NULL;
ListNode *q = p->next;
p->next = NULL;
ListNode* r;
while(q!=NULL){
r = q->next;
q->next = p;
p = q;
q = r;
}
reHead = p;
ListNode *p1 = head;
ListNode *p2 = reHead;
while(p1!=NULL){
q = p1->next;
r = p2->next;
p1->next = p2;
if(q!=NULL)
p2->next = q;
p1 = q;
p2 = r;
}
}
};
0 0
原创粉丝点击