Junior — Middle
What steps are taken to add a new element to a linked list?
sobes.tech AI
Answer from AI
Adding a new element to a linked list typically involves the following steps:
- Creating a new node with the desired value.
- Determining the insertion point (at the beginning, end, or middle of the list).
- Updating links:
- If inserting at the beginning: the new node points to the current first element, then the head of the list is updated to the new node.
- If inserting at the end: traverse the list to the last node, change its link to the new node.
- If inserting in the middle: find the node before the insertion point, update links so that the new node is between them.
Example of inserting at the beginning of a linked list in Java:
class Node {
int data;
Node next;
Node(int data) { this.data = data; }
}
class LinkedList {
Node head;
void addFirst(int value) {
Node newNode = new Node(value);
newNode.next = head;
head = newNode;
}
}