#include <stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;
};
struct node * Insert_beg(struct node *head, int s){
struct node *e = malloc(sizeof(struct node));
e->data = s;
e->link = head;
return e;
}
struct node * Insert_end(struct node *head, int s){
struct node *ptr;
struct node *e = malloc(sizeof(struct node));
e->data = s;
ptr = head;
while(ptr->link!=NULL){
ptr = ptr->link;
}
ptr->link = e;
e->link = NULL;
return head;
}
struct node * Insert_pos(struct node *head, int s, int pos){
struct node *i; // i is a position of curser
struct node *e = malloc(sizeof(struct node));
i = head;
int j = 0;
while(j!=pos-1){
i = i->link;
j++;
}
e->data = s;
e->link = i->link;
i->link = e;
return head;
}
void display(struct node *ptr){
while(ptr!=NULL){
printf(" %d ",ptr->data);
ptr = ptr->link;
}
}
int main()
{
struct node *head;
struct node *a;
struct node *b;
head = malloc(sizeof(struct node));
a = malloc(sizeof(struct node));
b = malloc(sizeof(struct node));
head->data = 2;
head->link= a;
a->data = 3;
a->link = b;
b->data = 4;
b->link = NULL;
int m;
printf("Enter the Element to add at the begninning: ");
scanf("%d",&m);
head = Insert_beg(head,m);
printf("Enter the Element to add at the end: ");
scanf("%d",&m);
head = Insert_end(head,m);
printf("Enter which position you want to add: ");
int p;
scanf("%d",&p);
printf("Enter the Element to add at the end: ");
scanf("%d",&m);
head = Insert_pos(head,m,p);
display(head);
return 0;
}
Comments
Post a Comment