In-place rotation of singly linked list

Xiaobai just started learning data structure from Mr. Chen Yue. When he encountered the in-place rotation of a singly linked list, he struggled to figure it out. After watching multiple blogs, he understood it and recorded it.

First of all, there are two linked lists (at first when I looked at the main part, I thought there was only one linked list, old-head refers to the first one, and new-head refers to the last one. Later, when I looked at the function code, I found that it was not the case). The initial state is as shown below.

Let’s talk about the cycle at the end. Let’s start with the first sentence of the main body.

Let the next node pointed by old-head be assigned to a new structure node. It becomes like the picture below.

Then the second sentence.

Make old-head point to new-head. That’s what the picture below looks like.

 The image below makes it clearer.

Then proceed to the third statement. 

Reverse the current old header to the new header. As shown below.

 Then proceed to the fourth statement.

Update the old header. As shown below.

 In this way, the old-head transfer is successfully achieved.

Finally, look at the loop statement.

When the old linked list is not empty, the loop will continue, and the program will continue to perform the above operations until the old linked list is empty, at which time it will become the state shown in the figure below.

In this way, the in-place reversal of a singly linked list is successfully achieved.

(I am new to data structure and csdn, if there are any errors, I hope you can point them out, thank you)

 

 

 

 

Guess you like

Origin blog.csdn.net/m0_59885919/article/details/123373267