Linked list OJ—circular linked list||

Tip: After the article is written, the table of contents can be automatically generated. For how to generate it, please refer to the help document on the right.


Preface

世上有两种耀眼的光芒,一种是正在升起的太阳,一种是正在努力学习编程的你!一个爱学编程的人。各位看官,我衷心的希望这篇博客能对你们有所帮助,同时也希望各位看官能对我的文章给与点评,希望我们能够携手共同促进进步,在编程的道路上越走越远!


提示:以下是本篇文章正文内容,下面案例可供参考

1. Circular linked list question:

2. Method explanation:

Graphical analysis:

Problem-solving idea: Use the method of double pointers (slow, fast). At the beginning, let them both point to the head node of the linked list. The slow pointer takes one step at a time, and the fast pointer takes two steps at a time.

1: If the linked list does not have a loop, then the fast pointer reaches empty, the loop ends, and NULL is returned;

2: If the linked list has a ring, then the fast pointer goes through the ring first and circulates in the ring, and the slow pointer goes into the ring behind, which will produce a chasing effect, because the fast pointer takes two steps each time, the slow pointer takes one step each time, and the fast pointer Every time the slow pointer and the slow pointer go through a process in the ring, the distance between the two pointers is reduced by 1. The distance traveled by the fast pointer = 2 times the distance traveled by the slow pointer.

Code:

Two other situations:

2. If slow takes 1 step at a time and fast takes 3 steps at a time, will they definitely meet?

3. If slow takes n steps at a time and fast takes m steps at a time, will it definitely catch up? m>n>1

Distance reduction m-n (>= an integer of 1)

N%(m-n) == 0 Will definitely catch up


Summarize

Okay, this blog ends here. If you have a better point of view, please leave a message in time. I will watch it carefully and learn from it.
If you don’t accumulate steps, you can’t reach a thousand miles; if you don’t accumulate small streams, you can’t become a river or sea.

Guess you like

Origin blog.csdn.net/2301_79585944/article/details/134899690