143 Reorder List
969 ワード
Given a singly linked list L: 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
問題を解く構想.
これはもともとチェーンテーブルが別のチェーンテーブルに変換されたテーマです.しかし、変換方式があまりにも奇抜で、チェーンテーブルには向いていない(チェーンテーブルは削除クラスを挿入する操作や隣接要素間の操作に適している)、
コード#コード#
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}
. 問題を解く構想.
これはもともとチェーンテーブルが別のチェーンテーブルに変換されたテーマです.しかし、変換方式があまりにも奇抜で、チェーンテーブルには向いていない(チェーンテーブルは削除クラスを挿入する操作や隣接要素間の操作に適している)、
vector
で保存してから変換することにした.コード#コード#
class Solution {
public:
void reorderList(ListNode* head) {
vector res;
ListNode* s = head;
while (s != NULL){
res.push_back(s->val); s = s->next;
}
int l = 0, r = res.size()-1;
ListNode* t = head;
while (l <= r){
t->val = res[l++];
t = t->next;
if (t == NULL) break;
t->val = res[r--];
t = t->next;
if (t == NULL) break;
}
}
};