Showing posts with label ordered link list. Show all posts
Showing posts with label ordered link list. Show all posts

Saturday, May 21, 2016

WAP to create singly link list in sorted order

#include<stdio.h>
#include<conio.h>
struct node
{
int n;
struct node *next;
}*first=NULL,*temp,*temp1;
void insert(int x)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->n=x;
if(first==NULL)
{
temp->next=NULL;
first=temp;
}
else
{
temp1=first;
while(temp1->next->n<x && temp1->next!=NULL)
{
temp1=temp1->next;
}
if(temp1==first && temp1->n>x)
{
temp->next=first;
first=temp;
}
else
{
temp->next=temp1->next;
temp1->next=temp;
}
}
}
void display()
{
if(first==NULL)
{
printf("Stack is empty");
return;
}
temp=first;
while(temp!=NULL)
{
printf("\n%d",temp->n);
temp=temp->next;
}
}
void main()
{
int x;
char ch;
clrscr();
do
{
printf("\nEnter a value: ");
scanf("%d",&x);
insert(x);
fflush(stdin);
display();
printf("\nDo you want to contiune(Y/N):");
scanf("%c",&ch);

}while(ch=='y' || ch=='Y');
display();
getch();
}

Thursday, May 19, 2016

WAP to create stack using link list

#include<stdio.h>
#include<conio.h>
struct node
{
int n;
struct node *next;
}*top=NULL,*temp;
void push(int x)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->n=x;
if(top==NULL)
temp->next=NULL;
else
temp->next=top;
top=temp;
}
int pop()
{
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
top=temp->next;
return temp->n;
}
int peep(int p)
{
int i;
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
for(i=0;i<p-1 && temp!=NULL;i++)
temp=temp->next;
if(temp!=NULL)
return temp->n;
else
printf("Position not found");
}
void change(int x,int p)
{
int i;
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
for(i=0;i<p-1 && temp!=NULL;i++)
temp=temp->next;
if(temp!=NULL)
temp->n=x;
else
printf("Position not found");
}
void display()
{
if(top==NULL)
{
printf("Stack is empty");
return;
}
temp=top;
while(temp!=NULL)
{
printf("\n%d",temp->n);
temp=temp->next;
}
}
void main()
{
int x,p,ch;
clrscr();
do
{
printf("\n1.Push");
printf("\n2.Pop");
printf("\n3.Peep");
printf("\n4.Change");
printf("\n5.Display");
printf("\n6.Exit");
printf("\nEnter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter value:");
scanf("%d",&x);
push(x);
break;
case 2:
x=pop();
printf("\nDeleted value is: %d",x);
break;
case 3:
printf("\nEnter position: ");
scanf("%d",&p);
x=peep(p);
printf("\nValue at position %d is: %d",p,x);
break;
case 4:
printf("\nEnter value: ");
scanf("%d",&x);
printf("\nEnter position: ");
scanf("%d",&p);
change(x,p);
break;
case 5:
display();
break;
case 6:
printf("\nThank you");
break;
default:
printf("\nWorng choice");
}
}while(ch!=6);
getch();
}