[Linked list OJ—Reverse 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. Reverse linked list question:

2. Method explanation:

Solution one:

Problem-solving idea: The position of the original linked list remains unchanged, but the next pointer in each linked list is reversed to point to the left.

1. Create three variables, n1 points to NULL, n2 points to the address of the first node, and n3 points to the address of the second node (in order to save the address of the second node, because if the next point in the first node changes, The second node address will be lost if not saved in advance).

2. Let n2 point to n1, n1 moves to n2, n2 moves to n3, and n3 moves backward to save the address of the next node until n2 is judged to be empty and the cycle ends.

Code demo:

Solution two:

Problem-solving ideas: Create three pointer variables (cur, newhead, and next) and an empty linked list

1. Cur pointer variable: used to replace the first head node of the original linked list and traverse the linked list; next: used to save the address of the next node; newhead: used to point to the newly created empty linked list.

2. Continuously take the first node from the original linked list to the new linked list, and repeat the head insertion operation.

Code demo:


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/134893444
Recommended