-
Notifications
You must be signed in to change notification settings - Fork 243
Add First
Sar Champagne Bielert edited this page Apr 20, 2024
·
2 revisions
Unit 5 Session 2 (Click for link to problem statements)
Understand what the interviewer is asking for by using test cases and questions about the problem.
- What does the function return if
new_node
is added to an empty linked list?- The function should return the
new_node
as it becomes the head of the linked list, even if the list was previously empty.
- The function should return the
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Modify the linked list by inserting a new node at the beginning and updating the head of the list to this new node.
1) Set the `next` attribute of the `new_node` to the current `head` of the linked list.
2) Return `new_node`, as it is now the new head of the list.
- Returning the old
head
instead of thenew_node
. - Not handling the
next
attribute correctly, which could lead to losing the rest of the list.
def add_first(head, new_node):
new_node.next = head
return new_node