面试中常见链表问题8:重排链表

来源:互联网 发布:淘宝开店身份证要求 编辑:程序博客网 时间:2024/06/15 21:53
    给定一个单链表:L0->L1->...->Ln-1->Ln,重新排序以后返回L0->Ln->L1->Ln-1->L2->Ln-2...。    解析:(1)把单链表分割为前后两部分。(2)把后一部分链表反转。(3)把两部分链表交叉插入即可。
ListNode * reverseList(ListNode *head){if (head == NULL || head->next == NULL)return head;ListNode *pHead = new ListNode(INT_MAX);pHead->next = head;ListNode *p = head->next;head->next = NULL;while (p){ListNode *tmp = p;p = p->next;tmp->next = pHead->next;pHead->next = tmp;}return pHead->next;}void reorderList(ListNode* &head) {if (head == NULL || head->next == NULL)return;ListNode *slow = head;ListNode *fast = head;while (fast != NULL && fast->next != NULL){fast = fast->next->next;slow = slow->next;}ListNode *pHead1 = head;ListNode *pHead2 = slow->next;slow->next = NULL;pHead2 = reverseList(pHead2);while (pHead2 != NULL){ListNode *tmp2 = pHead1->next;ListNode *tmp = pHead2;pHead2 = pHead2->next;tmp->next = pHead1->next;pHead1->next = tmp;pHead1 = tmp2;}}
0 0