Daily coding challenges. It's free!
Heres how it works:
- Sign up to receive a coding interview question in your mailbox daily.
- Try to find a solution! It's fun, builds confidence and sharpens your problem-solving skills.
- (PRO Version) Receive solutions with complete analysis, and all previous problems/solutions.
Sample coding problem
Problem Statement: Given the head of a linked list and a key, delete the node containing the given key.
Implement a function delete_node(head, key) in Python that takes in the head of the linked list and a key, and deletes the node containing the given key from the list. The linked list should be implemented using a Node class, with each node storing an integer value and a reference to the next node in the list.
The function should handle the following edge cases:
- The linked list is empty
- The node with the given key is not in the list
Example Input:
# Initialize linked list linked_list = LinkedList() linked_list.append(10) linked_list.append(20) linked_list.append(30) linked_list.append(40) # Call delete_node function delete_node(linked_list.head, 20) The node with value 20 was deleted from the list.
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 return curr = self.head while curr.next: curr = curr.next curr.next = new_node def delete_node(self, key): if self.head is None: print("The list is empty.") return if self.head.data == key: self.head = self.head.next print("The node with value", key, "was deleted from the list.") return curr = self.head while curr.next: if curr.next.data == key: curr.next = curr.next.next print("The node with value", key, "was deleted from the list.") return curr = curr.next print("The node with value", key, "was not found in the list.")
This solution first checks if the linked list is empty. If it is, it returns a message indicating that the list is empty. If the head node contains the key, it updates the head reference to the next node, effectively deleting the head node.
Otherwise, the function iterates through the list, checking each node for the key. If the key is found, it updates the reference of the previous node to the next node, effectively deleting the current node. If the key is not found in the list, it returns a message indicating that the node was not found in the list.
We use the language Python. Why Python? Its considered one of the easiest programming languages to learn, thanks to its clear and concise syntax. It has a large and active community of developers, which means there are many resources available for learning and troubleshooting.
Practice, practice, practice: the more practice, the better you will become.
Sign up to start receiving free coding problems.
Have a great day!