How to reverse the linked list with python
Most people do not understand the knowledge points of this article "python how to reverse the linked list", so the editor summarizes the following contents, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to reverse the linked list python" article.
[title]
Reverses a single linked list.
Example:
Enter: 1-> 2-> 3-> 4-> 5-> NULL
Output: 5-> 4-> 3-> 2-> 1-> NULL
Advanced:
You can iterate or recursively reverse the linked list. Can you solve the problem in two ways?
[ideas]
Use three pointers p, Q, r to point to three adjacent nodes, where p.next is qmenq.next is r.
Modify the pointer to Q and move the three pointers p, Q and r, that is, q.next = pforce p = Q, Q = r r = r.next. Continuous circulation, and pay attention to modify head.next and head, the list can be flipped.
[code]
Python version
# Definition for singly-linked list.
# class ListNode:
# def _ _ init__ (self, val=0, next=None):
# self.val = val
# self.next = next
Class Solution:
Def reverseList (self, head: ListNode)-> ListNode:
# head is empty
If not head:
Return head
# p, Q, r are three adjacent nodes
# q.next points to p, while three pointers move backward
P, Q, r = head, head.next, head
While q:
R = q.next
Q.next = p
P = Q
Q = r
# modify head.next and head
Head.next = None
Head = p
Return p above is about the content of this article on "how to reverse the linked list in python". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.