LoginSignup
0
0

More than 3 years have passed since last update.

LeetCode: 206. Reverse Linked List

Last updated at Posted at 2020-01-08

問題の要約

連結リストの順序を逆にする問題

問題

問題へのリンク

回答1 stackの使用

データの順番を逆にする=FILO(First In Last Out)=stackとの発想から、stackでの回答を試みました。

stackへリストを一通り格納し、stackのtop()から順番にリストへ戻していく操作をしました。

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        stack<ListNode> ListStack;
        ListNode* cur=head; 
        while(cur!=NULL) {
            ListStack.push(*cur);
            cur = cur->next;
        }
        cur=head;
        while(!ListStack.empty()){
            ListNode* tmp=cur->next;
           *cur=ListStack.top();
            cur->next=tmp;
            cur=cur->next;
            ListStack.pop();
        }

        return head;
    }
};

Runtime: 8 ms (beats 78.33%)
Memory Usage: 9.4 MB (beats 22.9%)

解いた後でDisscussを眺めた所、stackを使ってる人は少数派だった模様。ただしRuntimeは上位21%なので、そこそこ早いのかなと思います。

後で別方法の回答も作りたいです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0