LeetCode - Reorder List

来源:互联网 发布:大数据概念的首次提出 编辑:程序博客网 时间:2024/05/17 23:48

Reorder List

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

#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;}



0 0
原创粉丝点击