Question:
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:将链表存入一个vector,vector的元素为ListNode*,然后从前后同时开始按一定方式进行重排换位。(因为是单链表,所以如果不用指针数组保存的话,每次都需要遍历一遍去找尾结点和尾结点的前一个结点,效率会非常低)。
思路2:把整个链表划分成2个等长的子链表,如果原链表长度为奇数,那么第一个子链表的长度多1。然后翻转第二个子链表。最后合并两个子链表。
以下是思路1的实现:
Solution (C++):/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(!head || !head -> next ) return;
vector<ListNode *> result;
ListNode *cur = head;
while (cur)
{
result.push_back(cur);
cur = cur -> next;
}
int len = result.size();
vector<ListNode *>::size_type left = 0;
vector<ListNode *>::size_type right = len - 1;
while (left < right)
{
result[left] -> next = result[right];
result[right--] -> next = result[++left];
}
result[left] -> next = NULL;
}
};

本文介绍了如何通过两种方法对单链表进行重新排列:一种是将链表存入vector中,然后从前后同时开始按一定方式进行重排;另一种方法是将链表划分为两个等长子链表,翻转其中一个子链表,最后合并两个子链表。实现了在不修改节点值的情况下对链表进行重新排列。
364

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



