Inserting and Traversing the elements of a linked list.
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
struct node {
int num;
struct node *next;
}*start;
void createmptylist(struct node**start) {
*start = NULL;
}
void traverse(struct node *start) {
struct node *p = start;
while (p != NULL) {
printf("%d \n", p->num);
p = p->next;
}
}
void insertatbegin(int item) {
struct node *p;
p = malloc(sizeof(struct node));
p->num = item;
if (start == NULL)
p->next = NULL;
else
p->next = start;
start = p;
}
void insertatend(int item) {
struct node *p, *loc;
p = malloc(sizeof(struct node));
p->num = item;
p->next = NULL;
if (start == NULL)
start = p;
else {
loc = start;
while (loc->next != NULL) {
loc = loc->next;
}
loc->next = p;
}
}
void insert_spe(int item, int position) {
struct node *p, *temp;
int k;
p =malloc(sizeof(struct node));
p->num = item;
p->next = NULL;
if (position == 0) {
p->next = start;
start = p;
return;
}
temp = start;
for (k = 0; k < position - 1 && temp != NULL; k++) {
temp = temp->next;
}
if (temp == NULL) {
printf("Invalid position\n");
free(p);
return;
}
p->next = temp->next;
temp->next = p;
}
void main() {
int choice, item, position;
clrscr();
createmptylist(&start);
do {
clrscr();
printf("1. Insert element at begin \n");
printf("2. Insert element at end position\n");
printf("3. Insert at specific position\n");
printf("4. Traverse the list in order\n");
printf("5. Exit\n");
printf("Enter your choice\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter the item\n");
scanf("%d", &item);
insertatbegin(item);
break;
case 2:
printf("Enter the item\n");
scanf("%d", &item);
insertatend(item);
break;
case 3:
printf("Enter the item\n");
scanf("%d", &item);
printf("Enter the position\n");
scanf("%d", &position);
insert_spe(item, position);
break;
case 4:
printf("\nTraverse the list:\n");
traverse(start);
getch(); // To pause and see the output
break;
case 5:
exit(0);
}
} while (choice != 5);
}