Skip to content

Instantly share code, notes, and snippets.

@mmanishh
Last active January 5, 2020 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmanishh/3817ba5d6f24fd56f796d104992f8c44 to your computer and use it in GitHub Desktop.
Save mmanishh/3817ba5d6f24fd56f796d104992f8c44 to your computer and use it in GitHub Desktop.
Convert List to LinkedList
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