1

i tried to program a iterator that returns the data in a linked list in a reversed way , from the last Node to the head node.

but for some reason only the first value us returned , the one that in the first recursion level.

=============code ===========

class Node:

    def __init__(self ,data ,next=None):

        self.data = data
        self.next = next

def foo(head):

    if head.next is None:
        yield head.data
    else:
        foo(head.next)
        yield head.data

=============================

head = Node('A',Node("B", Node("C")))

for x in foo(head):

    print(x)

======== result==========
A

========should be ========

A B C

Omar Einea
  • 2,478
  • 7
  • 23
  • 35
Dor.G
  • 23
  • 3
  • You never yield anything other than `head.data`. Just because you call `foo(head.next)` doesn't mean its result is automatically yielded. Try `yield from foo(head.next)` – Aran-Fey Jan 27 '18 at 10:18

1 Answers1

1

The following approach works to print a forward node list and a backward node list.

The Node class:

>>> class Node:
...     def __init__(self, data=None, next=None):
...             self.data = data
...             self.next  = next
...     def __str__(self):
...             return str(self.data)

A list with more than one node

>>> node1 = Node('A')
>>> node2 = Node('B')
>>> node3 = Node('C')

Linking nodes, the first node refer to the second, the second node refer to the third, and the third node is None

>>> node1.next = node2
>>> node2.next = node3

To print forward list

>>> def print_list(node):
...     while node:
...             print(node),
...             node = node.next
...     print
...
>>> print_list(node1)
A
B
C

To print backward list

>>> def print_backward(list):
...     if list == None: return
...     head = list
...     tail = list.next
...     print_backward(tail)
...     print(head),
...
>>> print_backward(node1)
C
B
A

For more details please refer

Ashok Kumar Jayaraman
  • 2,887
  • 2
  • 32
  • 40