“This is the first day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021”
preface
Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now
omg
Ha ha, is also a small algorithm problem to share, this problem is my face ali’s algorithm problem, at that time he did not understand what the meaning, ah, ashamed. Today, small six six with everyone to eat him again
The title
Given a linked list, swap adjacent nodes in pairs and return the swapped list.
You can’t just change the values inside a node, you need to actually swap nodes.
Example:
Given 1->2->3->4, you should return 2->1->4->3.
Let’s read the question together. In fact, the meaning of the question is still very simple: every 2 nodes are a group, and the nodes in each group interact with each other. Is like.
Problem solving a recurrence
So for recursion, let’s just say what we should focus on
- Recursive return value
- What is the exit of recursion (condition for termination of recursion)
- What logic does recursion do
In this case, they are as follows
- Return value: The sublist of completed exchanges
- Terminating condition: head is null or next is null, that is, there is currently no node or only one node and cannot be swapped
- The logic of the calling unit: head is a null pointer or next is a null pointer, i.e. there is currently no node or only one node and cannot be swapped
I mean, it’s abstract, I thought about it for a long time, but just to explain it, it’s like 1234, so the first recursion is 12 and the second recursion is 34 and then I put the result of the second recursion in the same place as the 2 and the 1. Look at the code. Think about it. Think about it
In the red circle is the solution, it’s A little bit of code, but it’s A lot to think about, but it’s using A central variable, like A and B are swapping, so I swap A first with C, then A and B, and then B is swapping with C. This part is true
Answer key 2
We think about it, is the kind of feeling their thinking is blocked, ah.
At the end
These 2 kinds of solutions are my reference to others, they can not write out, look at others’ ideas also want to think for a long time, every time I see others write recursion I feel that he is a fool. Ha ha also have this feeling, but the understanding is barely understandable, but their abstract can not come out of this thought, vegetables are original sin, DO not know friends, think clearly, next time to brush the simple question first.
Daily for praise
Ok, everybody, that’s all for this article, you can see people here, they are real fans.
Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article
Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!