Reversing a linked list in python

前端 未结 11 2369
失恋的感觉
失恋的感觉 2020-12-08 12:28

I am asked to reverse a which takes head as parameter where as head is a linked list e.g.: 1 -> 2 -> 3 which was returned from a function already defined I tried to implemen

相关标签:
11条回答
  • 2020-12-08 13:12

    U can use mod function to get the remainder for each iteration and obviously it will help reversing the list . I think you are a student from Mission R and D

    head=None   
    prev=None
    for i in range(len):
        node=Node(number%10)
        if not head:
            head=node
        else:
            prev.next=node
        prev=node
        number=number/10
    return head
    
    0 讨论(0)
  • 2020-12-08 13:12

    The accepted answer doesn't make any sense to me, since it refers to a bunch of stuff that doesn't seem to exist (number, node, len as a number rather than a function). Since the homework assignment this was for is probably long past, I'll post what I think is the most effective code.

    This is for doing a destructive reversal, where you modify the existing list nodes:

    def reverse_list(head):
        new_head = None
        while head:
            head.next, head, new_head = new_head, head.next, head # look Ma, no temp vars!
        return new_head
    

    A less fancy implementation of the function would use one temporary variable and several assignment statements, which may be a bit easier to understand:

    def reverse_list(head):
        new_head = None  # this is where we build the reversed list (reusing the existing nodes)
        while head:
            temp = head  # temp is a reference to a node we're moving from one list to the other
            head = temp.next  # the first two assignments pop the node off the front of the list
            temp.next = new_head  # the next two make it the new head of the reversed list
            new_head = temp
        return new_head
    

    An alternative design would be to create an entirely new list without changing the old one. This would be more appropriate if you want to treat the list nodes as immutable objects:

    class Node(object):
        def __init__(self, value, next=None): # if we're considering Nodes to be immutable
            self.value = value                # we need to set all their attributes up
            self.next = next                  # front, since we can't change them later
    
    def reverse_list_nondestructive(head):
        new_head = None
        while head:
            new_head = Node(head.value, new_head)
            head = head.next
        return new_head
    
    0 讨论(0)
  • 2020-12-08 13:12
    def reverseLinkedList(head):
    
        current =  head
        previous = None
        nextNode = None
    
        while current:
    
            nextNode = current.nextNode
            current.nextNode = previous
    
            previous = current
            current = nextNode
    
        return previous
    
    0 讨论(0)
  • 2020-12-08 13:15

    Here is a way to reverse the list 'in place'. This runs in constant time O(n) and uses zero additional space.

    def reverse(head):
      if not head:
        return head
      h = head
      q = None
      p = h.next
      while (p):
        h.next = q
        q = h
        h = p
        p = h.next
      h.next = q
      return h
    

    Here's an animation to show the algorithm running.
    (# symbolizes Null/None for purposes of animation)

    0 讨论(0)
  • 2020-12-08 13:18

    You can do the following to reverse a singly linked list (I assume your list is singly connected with each other).

    First you make a class Node, and initiate a default constructor that will take the value of data in it.

    class Node:
        def __init__(self, data):
            self.data = data
            self.next = None
    

    This solution will reverse your linked list "iteratively". I am making a class called SinglyLinkedList which will have a constructor:

    class SinglyLinkedList:
        def __init__(self):
            self.head = None
        
    

    then I have written a method to reverse the list, print the length of the list, and to print the list itself:

    # method to REVERSE THE LINKED LIST
    def reverse_list_iterative(self):
        prev = None
        current = self.head
        following = current.next
        while (current):
            current.next = prev
            prev = current
            current = following
            if following:
                following = following.next
        self.head = prev
    
            
    # Method to return the length of the list
    def listLength(self):
        count = 0
        temp = self.head
        while (temp != None):
            temp = temp.next
            count += 1
        return count
    
    # Method to print the list
    def printList(self):
        if self.head ==  None:
            print("The list is empty")
        else:
            current_node = self.head
            while current_node:
                print(current_node.data, end = " -> ")
                current_node = current_node.next
            
            if current_node == None:
                print("End")`
    

    After that I hard code the list, and its contents and then I link them

    if __name__ == '__main__':
        sll = SinglyLinkedList()
        sll.head = Node(1)
        second = Node(2)
        third = Node(3)
        fourth = Node(4)
        fifth = Node(5)
    
        # Now linking the SLL
        sll.head.next = second
        second.next = third
        third.next = fourth
        fourth.next = fifth
    
        print("Length of the Singly Linked List is: ", sll.listLength())
        print()
        print("Linked List before reversal")
        sll.printList()
        print()
        print()
        sll.reverse_list_iterative()
        print("Linked List after reversal")
        sll.printList()
    

    Output will be:

    Length of the Singly Linked List is: 5

    Linked List before reversal 1 -> 2 -> 3 -> 4 -> 5 -> End

    Linked List after reversal 5 -> 4 -> 3 -> 2 -> 1 -> End

    enter image description here

    0 讨论(0)
提交回复
热议问题