55.3k views
5 votes
Write a function that appends a new node that has data at the end of the linked list. The function returns a pointer to the from of the list (head)

•The function has 2 parameter: a pointer to the first node in a linked list and the data to be added
•The function must handle three cases:
a)Linked list is empty
b)Linked list has one node
c)Linked list has multiple nodes

1 Answer

4 votes

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:

  1. Create a new node with the given data.
  2. If the linked list is empty, make the new node the head of the list.
  3. If the linked list has only one node, make the new node the next node of the current node.
  4. If the linked list has multiple nodes, traverse to the last node and make the new node the next node of the last node.
  5. 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;
}

User Garvice
by
8.1k points