Id: 221-15-4706
1. #include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void insertAfter(struct Node* prevNode, int newData) {
if (prevNode == NULL) {
printf("The given previous node cannot be NULL.");
return;
}
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.");
return;
}
newNode->data = newData;
newNode->next = prevNode->next;
prevNode->next = newNode;
}
int main() {
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
struct Node* third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 4;
third->next = NULL;
insertAfter(second, 3);
return 0;
}
2.#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* insertAtHead(struct Node* head, int newData) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed.");
return head;
}
newNode->data = newData;
newNode->next = head;
return newNode;
}
int main() {
struct Node* head = (struct Node*)malloc(sizeof(struct Node));
struct Node* second = (struct Node*)malloc(sizeof(struct Node));
head->data = 2;
head->next = second;
second->data = 4;
second->next = NULL;
head = insertAtHead(head, 1);
return 0;
}