Linkedlist C
Linkedlist C
h>
#include <stdlib.h>
struct node {
int data;
struct node *link;
};
int append() {
ptr = (struct node *)malloc(sizeof(struct node));
if (start == NULL) {
start = ptr;
return 1;
}
temp = start;
void add_beg() {
ptr = (struct node *)malloc(sizeof(struct node));
if (start == NULL) {
ptr->link = NULL;
start = ptr;
return;
}
ptr->link = start;
start = ptr;
}
void del_end() {
if (start == NULL) {
printf("Linked list is empty\n");
return;
}
if (start->link == NULL) {
temp = start;
start = NULL;
free(temp);
return;
}
p = start;
temp = start->link;
p->link = NULL;
free(temp);
}
void display() {
temp = start;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->link;
}
}
int count() {
q = start;
int c = 0;
while (q != NULL) {
c++;
q = q->link;
}
return c;
}
void add_any_pos() {
int i, pos;
printf("\nEnter the position where you want to insert the node: ");
scanf("%d", &pos);
if (pos == 1) {
ptr->link = start;
start = ptr;
return;
}
temp = start;
for (i = 0; i < pos - 1 && temp != NULL; i++) {
temp = temp->link;
}
ptr->link = temp->link;
temp->link = ptr;
}
void traverse() {
temp = start;
if (temp == NULL) {
printf("Linked list is empty\n");
return;
}
printf("\n");
}
void deleteBeg() {
if (start == NULL) {
printf("Linked list is empty\n");
return;
}
temp = start;
start = start->link;
free(temp);
}
void deleteAtAnyPos() {
int pos;
printf("Enter position: ");
scanf("%d", &pos);
if (start == NULL) {
printf("Linked list is empty\n");
return;
}
if (pos == 1) {
deleteBeg();
return;
}
p = start;
temp = start->link;
int i;
for ( i = 0; i < pos - 1 && temp != NULL; i++) {
p = temp;
temp = temp->link;
}
if (temp == NULL) {
printf("Invalid position\n");
return;
}
p->link = temp->link;
free(temp);
}
void deleteKey() {
int k;
if (start == NULL) {
printf("Linked list is empty\n");
return;
}
temp = start->link;
p = start;
while (temp != NULL) {
if (temp->data == k) {
p->link = temp->link;
free(temp);
return;
}
p = temp;
temp = temp->link;
}
void create() {
int n, i;
printf("Enter the number of nodes: ");
scanf("%d", &n);
int main() {
create();
int op = 0;
while (op != 8) {
printf("\nMENU\n1. Insert at beginning\n2. Insert at end\n3. Insert at position\n4. Traverse\
n5. Delete at start\n6. Delete at position\n7. Delete by key\n8. Exit\n");
printf("Enter your choice: ");
scanf("%d", &op);
switch (op) {
case 1:
add_beg();
break;
case 2:
append();
break;
case 3:
add_any_pos();
break;
case 4:
traverse();
break;
case 5:
deleteBeg();
break;
case 6:
deleteAtAnyPos();
break;
case 7:
deleteKey();
break;
case 8:
printf("Exiting program\n");
break;
default:
printf("Invalid option. Please enter a valid option.\n");
}
}
return 0;
}