class Solution {
public:
void reorderList(ListNode* head) {
// write your code here
if(head == NULL || head->next == NULL){
return;
}
ListNode *list1 = head;
ListNode *mid = findmid(head);
ListNode *list2 = reserve(mid->next);
mid->next = NULL;
ListNode *dummy = new ListNode(0);
ListNode *temp = dummy;
int index = 0;
while(list1!=NULL && list2!=NULL){
if(index%2 == 0){
temp->next = list1;
list1 = list1->next;
}
else{
temp->next = list2;
list2 = list2->next;
}
index++;
temp = temp->next;
}
if(list1!=NULL){
temp->next = list1;
}
if(list2!=NULL){
temp->next = list2;
}
head = dummy->next;
}
ListNode *findmid(ListNode *head){
ListNode *first = head;
ListNode *second = head->next;
while(second!=NULL && second->next!=NULL){
first = first->next;
second = second->next->next;
}
return first;
}
ListNode *reserve(ListNode *head){
ListNode *prev = NULL;
ListNode *cur = head;
ListNode *temp;
while(cur!=NULL){
temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
};143. Reorder List
最新推荐文章于 2020-05-10 11:40:52 发布
本文介绍了一种链表重构算法,该算法将链表分为两部分并反转后半部分,然后交错合并两部分链表。文章详细解释了如何寻找链表中点、反转链表以及交替合并两个链表的方法。
345

被折叠的 条评论
为什么被折叠?



