Here are some common operations in a singly linked list using C:
```
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
```
```
void insertAtBeginning(struct Node** headRef, int value) {
struct Node* newNode = createNode(value);
newNode->next = *headRef;
*headRef = newNode;
}
```
```
void insertAtEnd(struct Node** headRef, int value) {
struct Node* newNode = createNode(value);
if (*headRef == NULL) {
*headRef = newNode;
return;
}
struct Node* temp = *headRef;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
```
```
void insertAtPosition(struct Node** headRef, int position, int value) {
if (position < 1) {
printf("Invalid position!");
return;
}
if (position == 1) {
insertAtBeginning(headRef, value);
return;
}
struct Node* newNode = createNode(value);
struct Node* temp = *headRef;
for (int i = 1; i < position-1 && temp != NULL; i++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Invalid position!");
return;
}
newNode->next = temp->next;
stemp->next = newNode;
}
```
```
void deleteFirstNode(struct Node** headRef) {
if (*headRef == NULL) {
printf("List is already empty!");
return;
}
struct Node* temp = *headRef;
*headRef = (*headRef)->next;
free(temp);
}
```
```
void deleteLastNode(struct Node** headRef) {
if (*headRef == NULL) {
printf("List is already empty!");
return;
}
if ((*headRef)->next == NULL) {
free(*headRef);
*headRef = NULL;
return;
}
struct Node* temp = *headRef;
while (temp->next->next != NULL) {
temp = temp->next;
}
free(temp->next);
temp->next = NULL;
}
```
```
void deleteAtPosition(struct Node** headRef, int position) {
if (*headRef == NULL) {
printf("List is already empty!");
return;
}
if (position < 1) {
printf("Invalid position!");
return;
}
if (position == 1) {
deleteFirstNode(headRef);
return;
}
struct Node* temp = *headRef;
struct Node* prev = NULL;
for (int i = 1; i < position && temp != NULL; i++) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("Invalid position!");
return;
}
prev->next = temp->next;
free(temp);
}
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc