题目:
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}
.
题目分析:
1、边界情况:链表为空或者链表长度为1时,都可以不用做操作。
2、拆分最终的链表,发现前半段L0, L1, L2,...顺序没有变化;后半段Ln, Ln-1,Ln-2,...顺序颠倒。
思路:
1、找出中间节点,将链表分为前后两段。(可以找中间节点的前一个节点,因为要将该节点的next指向null,只不过翻转时向后在移动一个就好了)
2、将后半段链表翻转
3.、设一个新节点的next指向于head,从而在每次循环中都是先操作前半段,在操作后半段
4、注意控制好循环条件,链表总长度可能为奇数或者是偶数
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head)
{
if (head == nullptr || head->next ==nullptr) return;
ListNode* p = new ListNode(0);
p->next = head;
ListNode* p1 = head;
ListNode* middle = getPreMiddle(head); //中间节点的前一个节点
ListNode* p2 = reverseList(middle->next); // 先翻转后半段,在将middle指向null
middle->next = nullptr;
while (p1 != nullptr) //链表总长度为偶数时,直接结束循环
{
p->next = p1;
p1 = p1->next;
p = p->next;
if (p2 != nullptr) //链表总长度为奇数时,多指向一次前半段最后一个节点
{
p->next = p2;
p2 = p2->next;
p = p->next;
}
else
break;
}
}
ListNode* getPreMiddle(ListNode* head)
{
if (head == nullptr || head->next == nullptr) return head;
ListNode* pfast = head;
ListNode* pslow = head;
while (pfast->next != nullptr && pfast->next->next != nullptr)
{
pfast = pfast->next->next;
pslow = pslow->next;
}
return pslow;
}
ListNode* reverseList(ListNode* head)
{
if (head == nullptr || head->next == nullptr) return head;
if (head->next->next == nullptr)
{
ListNode* p = head->next;
head->next = nullptr;
p->next = head;
return p;
}
ListNode* pre = head;
ListNode* now = head->next;
ListNode* next = now->next;
pre->next = nullptr;
while (next != nullptr)
{
now->next = pre;
pre = now;
now = next;
next = next->next;
}
now->next = pre;
return now;
}
};
备注:第一次做medium级别的题,还是很开心的。自己判断循环条件的能力太弱,要多加练习。