您的位置:首页 > 其它

LeetCode - Reorder List

2014-02-13 17:47 267 查看
Reorder List

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}
.

#include <iostream>
#include <vector>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
void reorderList(ListNode *head) {
if (!head)
return;

int length = 0;
vector<ListNode *> vecList;

ListNode *trace = head;

while (trace) {
vecList.push_back(trace);
trace = trace->next;
length++;
}

int start = 0;
int tail = length - 1;
while (start < tail) {
vecList[start]->next = vecList[tail];
vecList[tail]->next = vecList[start+1];
start++;
tail--;
}

vecList[start]->next = NULL;
}
};

int main()
{
ListNode *head = new ListNode(1);
ListNode *trace = head;

trace->next = new ListNode(2);
trace = trace->next;

trace->next = new ListNode(3);
trace = trace->next;

trace->next = new ListNode(4);

trace = head;
while (trace) {
cout << trace->val << endl;
trace = trace->next;
}

Solution *so = new Solution();
so->reorderList(head);

trace = head;
while (trace) {
cout << trace->val << endl;
trace = trace->next;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: