Skip to content

876. Middle of the Linked List#22

Open
ryosuketc wants to merge 1 commit intomainfrom
876_middle_of_the_linked_list
Open

876. Middle of the Linked List#22
ryosuketc wants to merge 1 commit intomainfrom
876_middle_of_the_linked_list

Conversation

@ryosuketc
Copy link
Owner

### step2

* 2 pass も一応書いた。思ったより冗長になったけど、一応こっちのほうがわかりやすいかなという気はする。
* size (length) を求める関数だったので、例に倣って 1-index にしたが 0-index でもよかったかもしれない。ただその場合 head == nullptr のとき何を返すのかとか、関数名どうするかとか考慮すべき要素が増える気はする。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

抽象化するならば GetNth も用意したほうがいいのでは?

あと、速度を実測しての比較もよければ。2 pass のほうが少し遅いですかね。でもそんなに変わらないので、production ならこっちとりますかね。

public:
ListNode* middleNode(ListNode* head) {
// Return the second node when there are two "middle"s. 1-indexed.
int middle_index = GetListSize(head) / 2 + 1;
Copy link

@nodchip nodchip Nov 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自分なら for 文で書くと思います。

int middle_index = GetListSize(head) / 2;
ListNode* node = head;
for (int index = 0; index < middle_index; ++index) {
    node = node->next;
}
return node;

自分にはこちらのほうがシンプル見感じられます。好みの問題かもしれません。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants