Singly Linked List Programs (C)
1) Insert, Delete and Traverse operations (Beginning, End, Specific Position)
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
struct Node* head = NULL;
void insert_begin(int val) {
struct Node* new = malloc(sizeof(struct Node));
new->data = val;
new->next = head;
head = new;
}
void insert_end(int val) {
struct Node* new = malloc(sizeof(struct Node));
new->data = val;
new->next = NULL;
if (!head) {
head = new;
return;
}
struct Node* temp = head;
while (temp->next)
temp = temp->next;
temp->next = new;
}
void insert_pos(int val, int pos) {
if (pos == 1) {
insert_begin(val);
return;
}
struct Node* temp = head;
for (int i = 1; i < pos-1 && temp; i++)
temp = temp->next;
if (!temp) return;
struct Node* new = malloc(sizeof(struct Node));
new->data = val;
new->next = temp->next;
temp->next = new;
}
void delete_begin() {
if (!head) return;
struct Node* temp = head;
head = head->next;
free(temp);
}
void delete_end() {
if (!head) return;
if (!head->next) {
free(head);
head = NULL;
return;
}
struct Node* temp = head;
while (temp->next->next)
temp = temp->next;
free(temp->next);
temp->next = NULL;
}
void delete_pos(int pos) {
if (pos == 1) {
delete_begin();
return;
}
struct Node* temp = head;
for (int i = 1; i < pos-1 && temp; i++)
temp = temp->next;
if (!temp || !temp->next) return;
struct Node* del = temp->next;
temp->next = del->next;
free(del);
}
void traverse() {
struct Node* temp = head;
while (temp) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
------------------------------------------------------------
2) Rearrange elements of singly linked list in ascending order
void sort_list() {
struct Node *i, *j;
int temp;
for (i = head; i != NULL; i = i->next) {
for (j = i->next; j != NULL; j = j->next) {
if (i->data > j->data) {
temp = i->data;
i->data = j->data;
j->data = temp;
}
}
}
}
------------------------------------------------------------
3) Move last node to front of singly linked list
void move_last_to_front() {
if (!head || !head->next) return;
struct Node* sec_last = NULL;
struct Node* last = head;
while (last->next) {
sec_last = last;
last = last->next;
}
sec_last->next = NULL;
last->next = head;
head = last;
}