The first 281 Pian original works
Have you had this experience: to see other people's code, then look at it very clear, however, over time, can not write himself how come? This is how it happened, we could clearly. Others are thinking you can not copy and do not have prior to the formation of thinking, carved into the bone marrow, mental training required considerable period of time.
How important leetcode, needless to say, a small brush leetcode partners, have these experiences. I can not think of yourself, and read other people's code, also read, but in the future to do this question, may still get it working.
Take the reverse list, it will basically interview questions, this question is, if usually not trained in this area, thinking not nurtured, it is difficult to write accurate within a few minutes, do not believe you try it now. Such questions like, may be with us for the entire technology life, regardless of rank, it's like water and air, programmers should come in handy.
It may still be some small partners, that such knowledge linked list that he will never use, learn the muscle. He flashed a reason for high force grid, they'll make your coding of thinking, a higher level.
Ordinary people have advanced, more thinking, more hands-on, multi-summary. I can easily detect it again, reversing a linked list, we go together.
Iterative version of the thought process:
Variables provided always points to the head of the list curhead after inversion, is initially equal to the input val val list header, next to None, i.e., only one node.
In this case, the original head of the list points to the second node NATURAL prehead (if present), and we mark the subsequent node tmp, because then we have to destroy prehead next field, we call point is inverted the new head of the list curhead, so mark tmp is the most natural and simple.
Once prehead the next domain to curhead established, our new list has increased by a node, what makes curhead point to the new node.
As iteration, then we must point to the beginning of prehead we mark tmp, and so far one iteration, the perfect place.
Understand the above process, the iterative version of the code written in one minute, it is not a problem.
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None:
return None
curhead = ListNode(head.val)
prehead = head.next
while prehead is not None:
tmp = prehead.next
prehead.next = curhead
curhead = prehead
prehead = tmp
return curhead
Iterative process animation
The next time someone asks you again if a similar topic, give him a good show again.
Recommended reading:
How scored 10 algorithm engineers offer, not to be missed!
Python Data Analysis Learning Path personal summary
Python and algorithms Community
A good-looking point