-1

I am using recursion to reverse the linked list but not getting the result. Whenever I am using the following code for the input [1,2,3,4,5,6,-1], it shows me the result [1->None]. I am not getting where I am making the mistake. Please help me.

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

def takeInput():
    inputList = [int(ele) for ele in input().split()]
    head = None
    for i in inputList:
        if i == -1:
            break
        newNode = Node(i)
        if head is None:
            head = newNode
            tail = newNode
        else:
            tail.next = newNode
            tail = newNode
    return head

def printLL(head):
    while head is not None:
        print(str(head.data) + "->", end="")
        head = head.next 
    print("None")
    return

def reverseLL(head):
    if head is None or head.next is None:
        return head
    rest = reverseLL(head.next)
    head.next.next = head
    head.next = None
    return rest
   

head = takeInput()
printLL(head)
reverseLL(head)
printLL(head)
3
  • what is your expected out for [1,2,3,4,5,6,-1] Commented Feb 6, 2023 at 14:41
  • 1
    @It_is_Chris I think their data in is meant to be "1 2 3 4 5 6 -1"
    – JonSG
    Commented Feb 6, 2023 at 14:42
  • @JonSG for the input i believe you are correct and then the OP converts to a list of ints in the takeInput function but I am still not sure what the OP is looking for Commented Feb 6, 2023 at 14:45

1 Answer 1

1

The problem is in the main code: you're not taking the value returned by the reverseLL function, which is the new head. You should do:

head = reverseLL(head)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.