add last in list c
To add an element at the end of a list in C, you need to follow these steps:
- Define a structure or a data type to represent the elements of the list. For example, you can define a structure called
Node
that contains the data and a pointer to the next element in the list.
typedef struct Node {
int data;
struct Node* next;
} Node;
- Create a new node and assign the data you want to add to it. For example, if you want to add the value
5
to the list, you can create a new node and assign5
to itsdata
field.
Node newNode = (Node)malloc(sizeof(Node));
newNode->data = 5;
newNode->next = NULL;
- Traverse the list to find the last node. Start from the head of the list and keep moving to the next node until you reach the end of the list. The last node will have its
next
pointer set toNULL
.
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
- Set the
next
pointer of the last node to point to the new node you created in step 2.
current->next = newNode;
- Optionally, update the head of the list if necessary. If the list was empty before adding the element, you need to update the head to point to the new node.
if (head == NULL) {
head = newNode;
}
And that's it! The new element has been added at the end of the list. Remember to handle memory allocation and deallocation properly, and don't forget to free the memory when you're done with the list.