Complete Singly Linked list using C
Complete linked list, creation, insertion, deletion.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
int count=0,f=1;
struct node * head, *temp, *newnode, *stemp;
void create()
{ head=0;
int choice =1;
while(choice==1)
{
count++;
newnode=(struct node*)malloc(sizeof(struct node));
newnode->next=0;
printf("enter data");
scanf("%d",&newnode->data);
if(head==0)
{
head=newnode;
temp=newnode;
}
else
{
temp->next=newnode;
temp=newnode;
}
printf("Want another node: ");
scanf("%d",&choice);
}
}
void insertpos()
{
int choice=1,pos,i;
while(choice==1)
{
printf("enter the position of insertion");
scanf("%d",&pos);
if(pos==1)
{
count++;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&newnode->data);
//forming link
newnode->next=head;
head=newnode;
}
else if(pos==count-1)
{
count++;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&newnode->data);
newnode->next=0;
//forming link
temp=head;
while(temp->next!=0)
temp=temp->next;
temp->next=newnode;
}
else
{
count++;
newnode=(struct node*)malloc(sizeof(struct node));
printf("enter data");
scanf("%d",&newnode->data);
//forming link
temp=head;
i=1;
while(i<pos-1)
{
temp=temp->next;
i++;
}
newnode->next=temp->next;
temp->next=newnode;
}
printf("\nDo you want another insertion (0,1): ");
scanf("%d",&choice);
}
}
void delpos()
{
int choice,pos,i;
printf("enter the position of node you want to delete: ");
scanf("%d",&pos);
if(pos==1)
{
count--;
if(head!=0){
temp = head;
head=temp->next;
free(temp);}
if(head==0)
f=1; //indicates that the list is empty;
//so first create list;
}
else if(pos==count)
{
count--;
temp = head;
while(temp->next!=0)
{
stemp=temp;
temp=temp->next;
}
//temp is pointing to the last node;
//stemp is pointing to the last second node;
{stemp->next=0;
free(temp);}
}
else
{
count--;
i=1;
while(i<pos-1)
{
temp=temp->next;
i++;
}
stemp=temp->next;
//stemp is pointing to the node which is being deleted;
//temp is pointing to that node, which is just before the node being deleted;
temp->next=stemp->next;
free(stemp);
}
}
void listprint()
{
temp = head;
printf("size is: %d\n",count);
while(temp!=0)
{
printf("%d ",temp->data);
temp=temp->next;
}
}
void main()
{
int choice,conti=1;
while(conti==1)
{
printf("Press 1. to create list");
printf("\nPress 2. to insert in list");
printf("\nPress 3. to delete in list");
printf("\nPress 4. to print list");
printf("\nEnter your choice: ");
scanf("%d",&choice);
if(choice==1)
{
if(f==1)
{create();f=0;}
else
printf("list already created");
}
else if(f==1)
printf("list is empty, create list first");
else
{
if(choice==2)
insertpos();
else if(choice==3)
delpos();
else if(choice==4)
listprint();
else
printf("invalid choice");
}
printf("\nDo you want to continue(0,1): ");
scanf("%d",&conti);
}
}
Comments
Post a Comment