Skip to content

Hacktoberfest: Update Linked List - print_reverse method #2792

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 44 additions & 29 deletions data_structures/linked_list/print_reverse.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Program to print the elements of a linked list in reverse
from typing import List


class Node:
Expand All @@ -8,48 +8,63 @@ def __init__(self, data=None):

def __repr__(self):
"""Returns a visual representation of the node and all its following nodes."""
string_rep = ""
string_rep = []
temp = self
while temp:
string_rep += f"<{temp.data}> ---> "
string_rep.append(f"{temp.data}")
temp = temp.next
string_rep += "<END>"
return string_rep
return "->".join(string_rep)


def make_linked_list(elements_list):
def make_linked_list(elements_list: List):
"""Creates a Linked List from the elements of the given sequence
(list/tuple) and returns the head of the Linked List."""

# if elements_list is empty
(list/tuple) and returns the head of the Linked List.
>>> make_linked_list([])
Traceback (most recent call last):
...
Exception: The Elements List is empty
>>> make_linked_list([7])
7
>>> make_linked_list(['abc'])
abc
>>> make_linked_list([7, 25])
7->25
"""
if not elements_list:
raise Exception("The Elements List is empty")

# Set first element as Head
head = Node(elements_list[0])
current = head
# Loop through elements from position 1
for data in elements_list[1:]:
current.next = Node(data)
current = head = Node(elements_list[0])
for i in range(1, len(elements_list)):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@shellhub Thanks for the review and merge, I was hoping to improve the algorithm by using the generator as a part of my Hacktoberfest contribution for #2510. What was the reason for removing it for the regular iteration over a list?

i.e. (what I had before)

for data in (elements_list[i] for i in range(1, list_length)):

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This way need to generate a list and then iterate. It's slow.

Copy link
Member

@realDuYuanChao realDuYuanChao Oct 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

def fun1() -> None:
    my_list = []
    elements_list = [14, 52, 14, 12, 43]
    for i in range(0, len(elements_list)):
        my_list.append(i)


def fun2() -> None:
    my_list = []
    elements_list = [14, 52, 14, 12, 43]
    for data in (elements_list[i] for i in range(0, len(elements_list))):
        my_list.append(data)


if __name__ == '__main__':
    import timeit

    print(timeit.timeit("fun1()", setup="from __main__ import fun1", number=100000))
    print(timeit.timeit("fun2()", setup="from __main__ import fun2", number=100000))

output:
0.087008857
0.119698832

Copy link
Contributor Author

@shermanhui shermanhui Oct 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, good catch, @shellhub. That was informative! I only ran timeit against the list slicing. I should have checked the regular iteration as well. I guess it's also better to keep it simple! 😃

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How we Iris dataset from an online source. Read the dataset into a data structure, preferably
in a 2D array??? Anyone help me please its my assignment

current.next = Node(elements_list[i])
current = current.next
return head


def print_reverse(head_node):
"""Prints the elements of the given Linked List in reverse order"""

# If reached end of the List
if head_node is None:
return None
else:
# Recurse
def print_reverse(head_node: Node) -> None:
"""Prints the elements of the given Linked List in reverse order
>>> print_reverse([])
>>> linked_list = make_linked_list([69, 88, 73])
>>> print_reverse(linked_list)
73
88
69
"""
if head_node is not None and isinstance(head_node, Node):
print_reverse(head_node.next)
print(head_node.data)


list_data = [14, 52, 14, 12, 43]
linked_list = make_linked_list(list_data)
print("Linked List:")
print(linked_list)
print("Elements in Reverse:")
print_reverse(linked_list)
def main():
from doctest import testmod

testmod()

linked_list = make_linked_list([14, 52, 14, 12, 43])
print("Linked List:")
print(linked_list)
print("Elements in Reverse:")
print_reverse(linked_list)


if __name__ == "__main__":
main()