206. Reverse linked list (Python version)

Question : Given the head node head of the singly linked list, please reverse the linked list and return the reversed linked list.
insert image description here

Idea : If you continue to insert nodes into the head of a linked list, the earliest put-in node will be at the end of the list (that is, the tail node), and the node will be removed from the head of the list, and the last one will be the tail node. . That is to say, continuously removing nodes from the head of a table and adding them to the head of another node forms a reversal process. The operations of removing and adding are O(1), and the total time overhead is O(n), so this is an efficient inversion algorithm.
Here is the Python code :

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        cur = head
        pre = None
        while cur:
           pre ,cur.next,cur = cur,pre,cur.next
           # pre = cur 是指将链表的首结点取下
           # cur.next = pre  是指在首端插入取下的结点
           # cur = cur.next 是指不断移动结点
           # while cur 是指依次将链表中的结点取完
        return pre

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324339645&siteId=291194637