Reputation: 1
I am trying to turn a singly linked list into a list of integers in a recursive manner. I have attempted to write a function but it doesn't work as I intend it to.
The function should take in a list like Node(1, Node(2, None))
and should return a list of integers like [1, 2]
.
I have attempted to write the function below but the output I'm getting is [1]
. I'm not sure where I'm going wrong as I'm very new to recursion.
def linked(items: Optional[Cell]) -> List[int]:
if items is None:
return None
elif items.next is not None:
list_int = []
list_int.append(items.data)
linked(items.next)
return list_int
Here is the class definition for Cell:
class Cell:
data: int
next: Optional[Cell]
def __init__(self, data: int, next: Optional[Cell]):
"""Constructs a singly linked list."""
self.data = data
self.next = next
***edited to be more focused and clear
Upvotes: -3
Views: 736
Reputation: 381
I'd suggest defining a generic iter
method on the LinkedList, and using it to do whatever you want, like list of values for example:
from typing import Iterable
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def iter_LL(ll: ListNode | None) -> Iterable[ListNode]:
node = ListNode(next=ll)
while (node := node.next): yield node
sample_ll = LinkedNode(1, LinkedNode(7, LinkedNode(7, LinkedNode(6, None))))
nodes = iter_LL(sample_ll) # If you just want to iterate over nodes
values = map(lambda node: node.val, nodes) # If you want to iterate over values.
Incase you explicitly need only the values iterator, you can yeild node.val
in the iter_LL
function.
You can also override the __iter__
method to have a seamless experience, like so:
ListNode.__iter__ = iter_LL
Note: This will work even if you don't have access to the source file of ListNode
, which is the case in leetcode.
Upvotes: 0
Reputation: 1
This is my code for turning a linked list to a regular list. This code will work mainly for leetcode, it works for negative numbers among other things.
# Definition for singly-linked list.
# class ListNode:
# def __init_`enter code here`_(self, val=0, next=None):
# self.val = val
# self.next = next
def ToArray(x):
l=[]
p=[]
t=0
for i in str(x):
if i == '-' or i.isnumeric():
l.append(i)
t=1
elif t==1 and i != '-' and i.isnumeric()==False:
p.append(int(''.join(l)))
l=[]
t=0
return(p)
Upvotes: 0
Reputation: 41905
Attempting to fill in the code you didn't provide, is this roughly what you're trying to do:
class LinkedList():
def __init__(self, data, link):
self.data = data
self.link = link
def toList(self):
if self.link is None:
return [self.data]
return [self.data] + self.link.toList()
example = LinkedList(1, LinkedList(7, LinkedList(7, LinkedList(6, None))))
print(example.toList())
OUTPUT
> python3 test.py
[1, 7, 7, 6]
>
Upvotes: 0
Reputation: 275
I'm not sure what node is supposed to be but I guess what you want to do is create a list of integers from nested lists of integers. If so, here's a code that I think works fine:
def unpack_nested_lists(L):
list_of_integers = []
for element in L:
if type(element) is list:
list_of_integers += unpack_nested_lists(element)
else:
list_of_integers.append(element)
return list_of_integers
I hope it will help you out,
Paul
Upvotes: 0