0

I'm having a complex issue here with one of my questions for class, the question is:

Find the element in a singly linked list that's m elements from the end.

Following a few guides and reading questions on StackOverflow I was able to come up with the following code:

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

# Singly Linked List
class SinglyLinkedList:

    # Initiate current object as start of list.
    def __init__(self):
        self.head = None

    # Add new node to list at currect position.
    def add(self, new_data):
        node = Node(new_data)
        node.next = self.head
        self.head = node

    # Set head as starting point and walk through list.
    def Question5(self, index):
        walk = self.head
        while walk is not None:
            yield walk.data
            walk = walk.next

sll = SinglyLinkedList()
sll.add(1);
sll.add(4);
sll.add(3);
sll.add(8);
sll.add(1);
print ("Value at 4 is :", sll.Question5(4))
# ('Value at 4 is :', 1)
sll.add(0);
sll.add(0);
sll.add(0);
sll.add(0);
sll.add(0);
print ("Value at 0 is :", sll.Question5(0))
# ('Value at 0 is :', 0)
sll.add(22345643);
sll.add(12345643);
sll.add(14375643);
sll.add(12345633);
sll.add(12345647);
print ("Value at 12345643 is :", sll.Question5(12345643))
# ('Value at 12345643 is :', None)

However instead of my output being what I expect it to be my code shows this when ran:

('Value at 4 is :', <generator object Question5 at 0x7f9635bb3870>)
('Value at 0 is :', <generator object Question5 at 0x7f9635bb3870>)
('Value at 12345643 is :', <generator object Question5 at 0x7f9635bb3870>)

Does anyone know what I'm doing wrong in this situation? Thank you.

Calvin Ellington
  • 713
  • 3
  • 11
  • 21

1 Answers1

1

You don't need yield in that case.

The algorithm you need depends on whether you know the size of the liked list or not.

Size known

Given size of list n: Just return the n-m-th element of the list.

Size unknown

Two iterations

The simplest trick would be to iterate over the whole list first, counting how many elements it contains. Then you know the size n and get the element as described above.

Remembering m elements

You can also solve this in one iteration if you 'remember' the last m elements you've seen in the list. Then iterate until the end of the list and return the 'oldest' element you still remember.

Using two pointers

This last approach uses two pointers to two elements of the list that always have a distance of m elements. They are both moved simultaneously. If the first pointer reaches the end of the list, the second pointer exactly points to the element m elements from the end of the list.

See How to find nth element from the end of a singly linked list? for details. The code in that post is C++, but it shouldn't be too hard to understand.

Community
  • 1
  • 1
Felix
  • 6,131
  • 4
  • 24
  • 44