Monday 9 January 2017

Write a c program to implement single linked list to print like 5 4 4 3 3 2 2 1 1 0 by taking input as 1 2 3 4 5

#include<stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node * create(struct node *,int);
display(struct node *);
reverse(struct node *);
main()
{
int n;
struct node *head=NULL;
printf("\nenter a number\n");
scanf("%d",&n);
head=create(head,n);
//display(head);
reverse(head);
}
struct node * create(struct node *q,int n)
{
int i;
struct node *newnode,*c;
for(i=1;i<=n;i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=i;
newnode->next=NULL;
if(q==NULL)
q = newnode;
else
{
c=q;
while(c->next != NULL)
c=c->next;
c->next=newnode;
}
}
return q;
}

display(struct node *p)
{
while(p!=NULL)
{
printf("\t%d\t%d",p->data,p->data-1);
p=p->next;
}
}
reverse(struct node *p)
{
struct node *q,*r;
q=NULL;
while(p != NULL)
{
r=q;
q=p;
p=p->next;
q->next=r;
}
p=q;
display(p);
}

No comments:

Post a Comment