Final answer:
To append a new node at the end of a linked list, you can create a new node with the given data and handle three cases: empty linked list, linked list with one node, and linked list with multiple nodes.
Step-by-step explanation:
To append a new node at the end of a linked list, you can follow these steps:
- Create a new node with the given data.
- If the linked list is empty, make the new node the head of the list.
- If the linked list has only one node, make the new node the next node of the current node.
- If the linked list has multiple nodes, traverse to the last node and make the new node the next node of the last node.
- Return the head (first node) of the linked list.
Here's an example implementation in C++:
struct Node {
int data;
Node* next;
};
Node* appendNode(Node* head, int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = nullptr;
if (head == nullptr) {
head = newNode;
} else {
Node* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
return head;
}