Flip list of Python data structures
- 2020-05-26 09:34:56
- OfStack
Flip 1 list
Example: give a linked list 1-
>
2-
>
3-
>
null, this flipped list is 3 minus
>
2-
>
1-
>
null
A simpler method is to use the method of removal. It is to create a new empty node, then traverse the whole list, and make the traversed nodes point to the header node of the new list.
In that case, the steps are as follows:
1. New 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
And, of course, there's another solution that's a little bit harder. We can write the code of in-situ inversion for the method of successively unchaining and linking nodes 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 should 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
# Connect the places where the chains are off
pre.next = cur.next
cur = pre.next
temp.next = dummy.next
dummy.next = temp
return dummy.next
# write your code here
It's important to remember that when you do the chain pick, don't forget to reconnect where you took it off
Thank you for reading, I hope to help you, thank you for your support of this site!