Leetcode206. Python implementation of reverse linked list

Time:2021-8-28
  • Title Requirements:

Leetcode206. Python implementation of reverse linked list

  • Idea:

    • Define a new head: myhead
    • Mark the next point of myhead as mynext
    • Each time, the next of myhead points to the new node, and the next of the new node points to mynext
    • Traverse the linked list until it is empty
  • Core code:
#New header node
myhead = ListNode()
#Mark the next of the header node
mynext = myhead.next
#The current value of traversing the linked list is cur
cur = head
#The next node to be inserted into the new linked list is cur.next
curnext = head.next

#When the current node is not empty:
while cur:
    #Point the next of the currently traversed node to mynext of the new linked list
    cur.next = mynext
    #The next of the header of the new linked list points to the current node
    myhead.next = cur
    #Update the value of mynext, because each insertion is after the new head
    mynext = myhead.next
    #Update the value of cur to the next node to be inserted
    cur = curnext
    #If curnext is not empty, curnext points to the next node of the original linked list
    if curnext:
        curnext = curnext.next
#Returns the next node of the new chain header
return myhead.next
  • Full code:

    • Add conditions to judge whether the given linked list is empty
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head is None:
            return None
            
        myhead = ListNode()
        mynext = myhead.next
        cur = head
        curnext = head.next

        while cur:
            cur.next = mynext
            myhead.next = cur
            mynext = myhead.next
            cur = curnext
            if curnext:
                curnext = curnext.next
                
        return myhead.next