'Python dictionary with values as singly linked lists
I have been trying to create a Python dictionary with values as singly linked lists. My code looks okay resulting correct keys. However each key yield the same value, do not know why. Please reply if you have any solution, code has been given below.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
tail = self.head
while tail.next:
tail = tail.next
tail.next = new_node
def create_two_ll(self, lists):
ll_dict = {}
for i in range(len(lists)):
for data in lists[i]:
self.append(data)
ll_dict[f"ll{i}"] = ll
print(ll_dict)
print(ll_dict["ll0"].head.next.next.next.data)
print(ll_dict["ll1"].head.next.next.next.data)
return ll_dict
if __name__ == "__main__":
ll = LinkedList()
ll.create_two_ll([[1,3,5], [2,4,6]])
Output (wrong):
{'ll0': <__main__.LinkedList object at 0x7feead82c850>}
{'ll0': <__main__.LinkedList object at 0x7feead82c850>, 'll1': <__main__.LinkedList object at 0x7feead82c850>}
2
2
Solution 1:[1]
i solved it another way but im not sure its ok
i hope it'll trigger better way in your mind
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
tail = self.head
while tail.next:
tail = tail.next
tail.next = new_node
def create_two_ll(self, lists):
ll_dict = {}
for i in range(len(lists)):
for data in lists[i]:
self.append(data)
ll_dict[f"ll{i}"] = data
print(ll_dict)
return ll_dict
if __name__ == "__main__":
ll = LinkedList()
ll.create_two_ll([[1,3,5], [2,4,6],[7,9,11]])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashkan Goleh Pour |
