Last active
January 5, 2020 16:42
-
-
Save mmanishh/3817ba5d6f24fd56f796d104992f8c44 to your computer and use it in GitHub Desktop.
Convert List to LinkedList
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node: | |
def __init__(self, val, next_node=None): | |
self.val = val | |
self.next_node = next_node | |
def __repr__(self): | |
return f'Node({self.val})' | |
# function to convert normal list to linked list | |
def from_list(alist): | |
if len(alist) == 1: | |
return Node(alist[0]) | |
return Node(alist[0], next_node=from_list(alist[1:])) | |
alist = [4, 5, 6, 7, 8] | |
#converting to linked list | |
linked_list = from_list(alist) | |
# Traversal of LinkedList | |
def traverse(node): | |
if node: | |
yield node | |
yield from traverse(node.next_node) | |
# Traversal of Tree | |
def traverse_tree(node): | |
if node: | |
yield from traverse_tree(node.left) | |
yield node | |
yield from traverse_tree(node.right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment