Reputation: 39
How do you access data in a linked list? Mainly, I have two specific questions. I'm a beginner in python and just learning linked lists so bear with me if this seems like a stupid question.
I have a linked list of nodes where each node is an instance of a class.
How do I retrieve the node in the linked list with a certain instance attribute = x?
I have a linked list of nodes where each node is a dictionary. How do I search for a node in the linked list with a certain key in Python?
Currently, I am unable to access the information in the node except for printing it using the str method.
Upvotes: 0
Views: 8319
Reputation: 647
Data in a linked list is accessed by traversing the list. You need to start at the head, check if the data it contains is what you're looking for, and traverse to the next node if it isn't.
So, making some assumptions about your implementation of linked lists:
You can do this with a function that returns None if the desired data attribute value isn't in the linked list. I'll assume your linked list nodes have a method, next_node, which returns None if it's the tail instance.
def traverse_to_desired_node(head : LinkedListNode, desired : Any):
node = head
while node.data != desired:
node = node.next_node()
if node is None:
return None
return node
A similar approach will work:
def traverse_to_desired_node(head : dict, desired : str):
node = head
while desired not in node:
node = node['next']
if node is None:
return None
return node
Now, with either approach, you can set a variable to the node:
node = traverse_to_node(head, 'desired')
Then, if it's a class instance, you can access the data attribute of that node:
print(node.data)
Or, if it's a dict, access the desired key:
print(node['desired'])
Upvotes: 1
Reputation: 4347
Usually you just need to define a recursive function. Assuming your linked list is defined as follows:
class Node:
def __init__(self, val):
self.val = val
self.next = None
Now traversing the list and finding a node with a specific value is fairly easy:
def find(node: Node, search_val):
if not node:
return None
else:
if node.val == search_val:
return node
else:
return find(node.next, search_val)
Similarly you can modify this function to check whether node.val
is a dictionary and whether it has a certain key.
Question 2 is phrased in a strange way. Node cannot be a dictionary. It has to be some form of Node class. It can contain a dictionary, but it can't be one.
Upvotes: 2