Flip linked list of Python data structure and flip of python Data Structure
Flip a linked list
Example: A chain table 1-> 2-> 3-> null. The flipped chain table is 3-> 2-> 1-> null.
A simple method is to use the "removal" method ". It is to first create an empty node, then traverse the entire linked list, and point the nodes in turn to the first node of the new linked list.
For example, the steps are as follows:
1. Create an empty node: None
2. 1-> None
3. 2-> 1-> None
4. 3-> 2-> 1-> None
The code is very simple:
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: You should return the head of the reversed linked list. Reverse it in-place. """ def reverse(self, head): temp = None while head: cur = head.next head.next = temp temp = head head = cur return temp # write your code here
Of course, there is a more difficult solution. We can write the code for in-situ turning by means of node chain extraction and link in the linked list:
"Definition of ListNode class ListNode (object): def _ init _ (self, val, next = None): self. val = val self. next = next "class Solution:" @ param head: The first node of the linked list. @ return: You shoshould return the head of the reversed linked list. reverse it in-place. "" def reverse (self, head): if head is None: return head dummy = ListNode (-1) dummy. next = head pre, cur = head, head. next while cur: temp = cur # link the link to pre. next = cur. next cur = pre. next temp. next = dummy. next dummy. next = temp return dummy. next # write your code here
Note that you should not forget to connect the removed part to the link during the chain extraction process.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!