Complementary task for topic: 11
M Nemeth · 2023-08-29 15:21:04.634218'
Linked list basic operations
Linked list basic operations
Implement a singly linked list (data: ineteger) and write functions to add elements to the front and end of the list, print the list, and calculate its length.
Hint: Drawing always help to figure out what to do!
Solution
#include
#include
// Define the structure for a node in the singly linked list
struct Node {
int data;
struct Node* next;
};
// Function to create a new node with the given data
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to add a new node at the front of the linked list
void addToFront(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// Function to add a new node at the end of the linked list
void addToEnd(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// Function to print the elements of the linked list
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// Function to calculate the length of the linked list
int listLength(struct Node* head) {
int length = 0;
struct Node* current = head;
while (current != NULL) {
length++;
current = current->next;
}
return length;
}
int main() {
struct Node* head = NULL;
addToFront(&head, 3);
addToFront(&head, 2);
addToFront(&head, 1);
printf("Linked list after adding elements to the front: ");
printList(head);
addToEnd(&head, 4);
addToEnd(&head, 5);
printf("Linked list after adding elements to the end: ");
printList(head);
int length = listLength(head);
printf("Length of the linked list: %d\n", length);
return 0;
}