重新排列链表Reorder List

在leetcode中题目是这样描述的:

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 合并两部分。代码如下:

#include
#include
using namespace std;
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };


class Solution {
public:
void reorderList(ListNode *head) {
ListNode *tmp_resultListNode = new ListNode(0);  //临时的结果链表在不断往后
ListNode *resultListNode = tmp_resultListNode;   //所以需要一个最终结果链表指向这个地址
bool flag = true;
ListNode *rightListNode = findListMidNode(head);  //找到后一半的链表
ListNode *reserveRightListNode = reserveList(rightListNode);  //求后一半链表的逆
ListNode *leftListNode = head;  //这时的head只有前一半,因为在findListMidNode中被截断了
while(leftListNode!=NULL || reserveRightListNode!=NULL)  //只要两个链表不为空,则进行合并
{
if(flag)  //为true,则并前面
{
tmp_resultListNode->next = leftListNode;
leftListNode = leftListNode->next;

}
else    //为false,则并后面
{
tmp_resultListNode->next = reserveRightListNode;
reserveRightListNode = reserveRightListNode->next;
}
tmp_resultListNode = tmp_resultListNode->next;  //临时结果链表推后
flag = !flag;
}
head = resultListNode->next;  //将最终结果付给头指针
}
ListNode *findListMidNode(ListNode *head)  //寻找一个链表的中间指针,并将链表分成两部分
{
if(head==NULL) return head;
ListNode *p = head;
ListNode *q = p->next;
while (q!=NULL && q->next!=NULL)
{
p=p->next;q = q->next->next;
}
q = p->next;p->next=NULL;
return q;
}
ListNode *reserveList(ListNode *head)  //对链表求逆
{
if(head==NULL)return head;
ListNode *p = head;
ListNode *tmp_resultList = new ListNode(0);
ListNode *resultList = tmp_resultList;
vectortmp_val;   //保存顺序链表得到的结果
while (p!=NULL)
{
tmp_val.push_back(p->val);
p=p->next;
}
for (int i =tmp_val.size()-1;i>=0;i--)  //逆向保存链表
{
tmp_resultList->next = new ListNode(tmp_val[i]);
tmp_resultList = tmp_resultList->next;
}
return resultList->next;  //返回结果
}
};
void main()
{
Solution s;
ListNode *head1 = new ListNode(2);
head1->next = new ListNode(4);
head1->next->next = new ListNode(6);
head1->next->next->next = new ListNode(3);
head1->next->next->next->next = new ListNode(5);
head1->next->next->next->next->next = new ListNode(1);
s.reorderList(head1);
while(1);
}

你可能感兴趣的:(leecode编程练习)