diff --git a/206. Reverse Linked List.md b/206. Reverse Linked List.md new file mode 100644 index 0000000..2154272 --- /dev/null +++ b/206. Reverse Linked List.md @@ -0,0 +1,92 @@ +# step1 +- 入力をスタックに入れていって、popしていけば良さそう + +```python +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + reverse_node = ListNode() + dummy= reverse_node + stack = [] + while node is not None: + stack.append(node.val) + node = node.next + while stack: + reverse_node.next = ListNode(stack.pop()) + reverse_node = reverse_node.next + return dummy.next +``` + +# step2 +- PRなどを見る +- スタックではなく繋ぎ変える方法もある(出題意図としてはこっち?) + - https://github.com/olsen-blue/Arai60/pull/7/changes#r1904334523 + - このPRのリンク先の繋ぎ変えの読んでコードを追ってみたが結構短いのに時間がかかってしまった + - 紙に書いて考えた時にnode.next = lastFixed_nodeでnode.nextを切り離して書いて、nodeを更新していなかった。 + - 紙の端っこの少スペースで書いていたので、変数の値を同じ個所で斜線で消して上書きしていた。そのため途中で今の状態がよくわからなくなったし、どこでミスしたのかのふりかえりもしにくくなった + - コードの流れは分かったが、なぜこれで出来るのかが腹落ちしていない感覚 + - https://discord.com/channels/1084280443945353267/1355246975309844550/1355898121460252784 + - これの3のイメージかな、コードから具体的なイメージが書けるようにしたい +- https://peps.python.org/pep-0008/#descriptive-naming-styles + - PEP8では関数名と変数名は小文字で単語間はアンダースコアでつなげる +- 再帰のやり方もある、が今回は軽く目を通す程度にしておいて次に進む + - https://discord.com/channels/1084280443945353267/1231966485610758196/1239417493211320382 + +```python +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + last_fixed_node = None + + while node: + not_fixed_node = node.next + node.next = last_fixed_node + lastFixed_node = node + node = notFixed_node + + return lastFixed_node +``` + +# step3 + +```python +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + last_fixed_node = None + while node: + not_fixed_node = node.next + node.next = last_fixed_node + last_fixed_node = node + node = not_fixed_node + return last_fixed_node +``` +```python +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + last_fixed_node = None + while node: + not_fixed_node = node.next + node.next = last_fixed_node + last_fixed_node = node + node = not_fixed_node + return last_fixed_node +``` +```python +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + node = head + last_fixed_node = None + while node: + not_fixed_node = node.next + node.next = last_fixed_node + last_fixed_node = node + node = not_fixed_node + return last_fixed_node +```