Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

I'm approached to reverse a which accepts head as the parameter where as head is a connected linked list e.g.: 1 - > 2 - > 3 which was gotten back from a capacity previously characterized I attempted to execute the function reverse_linked_list thusly:

def reverse_linked_list(head):

    temp = head

    head = None

    temp1 =

    temp2 = = None = temp1 = temp

    return temp2

class Node(object):

    def __init__(self,value=None):

        self.value = value = None

    def to_linked_list(plist):

    head = None

    prev = None

    for element in plist:

        node = Node(element)

        if not head:

            head = node


   = node

        prev = node

    return head

    def from_linked_list(head):

    result = []

    counter = 0

    while head and counter < 100: # tests don't use more than 100 nodes, so bail if you loop 100 times.


        head =

        counter += 1

    return result

    def check_reversal(input):

        head = to_linked_list(input)

        result = reverse_linked_list(head)

        assert list(reversed(input)) == from_linked_list(result)

It is brought along these lines: check_reversal([1,2,3]). The function I have composed for switching the list is giving [3,2,1,2,1,2,1,2,1] and turns out just for a list of length 3. How might I sum it up for a list of length n?

1 Answer

0 votes
by (26.4k points)

You can utilize mod function to get the remainder of every cycle (Iteration) and clearly, it will helps in reversing the list.



for i in range(len):


    if not head:





return head

Interested to learn python in detail? Come and Join the python course.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 30, 2020 in Python by Sudhir_1997 (55.6k points)
0 votes
1 answer

Browse Categories