链表的重排序
问题描述:
Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-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}.
https://oj.leetcode.com/problems/reorder-list/点击打开链接
问题分析:
问题求解方法很简单,不做进一步分析。
定义:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
LisNode *head 为待处理的链表。
1. 将链表head分为两份,前半部分链表list1, 后半部分链表list2
2. list2逆序
3. list1, list2合并
void divideList(ListNode *head, ListNode* &list1, ListNode* &list2);
ListNode* reverse(ListNode *head);
ListNode* merge(ListNode *a, ListNode *b);
C语言代码:
void reorderList(ListNode *head)
{
/* 空表或者只有一个元素不需要reorder */
if (!head || !head->next)
{
return;
}
/*
* p1 前半部分头指针
* p2 后半部分头指针
* 前半部分可能比后半部分多一个元素
*
*/
ListNode *p1, *p2;
p1 = head;
ListNode *slow, *fast, *tail, *p;
slow = head;
fast = head;
while (fast)
{
tail = slow;
slow = slow->next;
fast = fast->next ? fast->next->next : NULL;
}
tail->next = NULL;
p2 = slow;
p = p2->next;
p2->next = NULL;
tail = p2;
while (p)
{
p2 = p;
p = p->next;
p2->next = tail;
tail = p2;
}
while (p1 && p2)
{
ListNode *prv = p1;
p1 = p1->next;
prv->next = p2;
p2 = p2->next;
prv->next->next = p1;
}
}