Sei sulla pagina 1di 3

#include<stdio.

h>
#include<stdlib.h>

struct node
{
int data;
struct node *link;
};

struct node *root = NULL;

int length(){
struct node *l=root;
int count =0;
while(l!=NULL){
l= l->link;
count++;
}
return count;
}

void append(){
struct node *temp ;

temp = (struct node *)malloc(sizeof(struct node));


printf("Enter node data : ");
scanf("%d", &temp->data);
temp->link = NULL;

if (root == NULL){
root = temp;
}
else{
struct node *t = root;

while (t->link != NULL)


{
t = t->link;
}
t->link = temp;

}
}

void addAtBeginning(){
struct node *temp;

temp = (struct node *)malloc(sizeof(struct node));


printf("Enter node data : ");
scanf("%d", &temp->data);

temp->link = root;
root = temp;
}

void addAtLocation(){
struct node *temp, *l;
int loc,i = 1;
printf("\nEnter location : ");
scanf("%d", &loc);

if (loc == 1)
addAtBeginning();
else if (loc == length())
append();
else if(loc > length())
printf("\nInvalid location");
else{
temp = (struct node *)malloc(sizeof(struct node));
printf("Enter node data : ");
scanf("%d", &temp->data);
temp->link = NULL;

l = root;
while(i<loc - 1){
l = l->link;
i++;
}
temp->link = l->link;
l->link = temp;
}
}

void traverse(){
struct node *temp = root;

while(temp != NULL){
printf("%d ", temp->data);
temp = temp->link;
}
}

void delete(){
struct node *temp = root, *t;
int loc, i;
printf("\nEnter location of node : ");
scanf("%d", &loc);

if (loc > length())


printf("\nInvalid location ");
else if (loc == 1){
root = temp->link;
temp->link = NULL;
free(temp);
}
else{
i = 1;
while(i < loc-1){
temp = temp->link;
i++;
}
t = temp->link;
temp->link = t->link;
t->link = NULL;
free(t);
}
}
int main(){
int choice;
while (1)
{
printf("\nEnter : \n1. Append \n2. Add at Beginning \n3. Add at Specific
Location ");
printf("\n4. Length \n5. Traverse \n6. Delete Node \n7. Exit\n");
printf("Enter your choice : ");
scanf("%d", &choice);

switch (choice)
{
case 1:
append();
break;
case 2:
addAtBeginning();
break;
case 3:
addAtLocation();
break;
case 4:
printf("Length is : %d",length());
break;
case 5:
traverse();
break;
case 6:
delete();
break;
case 7:
exit(0);
break;
default:
printf("\nWrong Choice\n");
break;
}
}

Potrebbero piacerti anche