Sunday, October 10, 2010

How to print the single linked list in reverse order without using array or memory?

/*
* list1.c
* Display the single linked list in reverse order
* Created on: Oct 11, 2010
* Author: Karthikeyan.D
*/

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct struNode
{
int nVal;
struct struNode *pstruNext;
}pstruStart;

int fnReversePrint(pstruStart* nTempLoation);

int fnReversePrint(pstruStart* nTempLoation)
{

if(nTempLoation->pstruNext != NULL)
{
fnReversePrint(nTempLoation->pstruNext);
printf("-->%d",nTempLoation->nVal);
}
else
{
printf("NULL-->%d",nTempLoation->nVal);
}

return 0;

}
int main()
{
struct struNode *pstruStart=NULL;
struct struNode *pstruNewnode,*pstruCurrent;

int nN;
int nI;

printf("enter the number of nodes\n");
scanf("%d",&nN);
for(nI=0;nI<nN;nI++)
{
pstruNewnode=(struct struNode*)malloc(sizeof(struct struNode));
printf("enter the data\n");
scanf("%d",&pstruNewnode->nVal);
pstruNewnode->pstruNext=NULL;
if(pstruStart==NULL)
{
pstruStart=pstruNewnode;
pstruCurrent=pstruNewnode;
}
else
{
pstruCurrent->pstruNext=pstruNewnode;
pstruCurrent=pstruNewnode;
}
}
printf("the linked list is\n");
pstruNewnode=pstruStart;
while(pstruNewnode!=NULL)
{
printf("%d----->",pstruNewnode->nVal);
pstruNewnode=pstruNewnode->pstruNext;
}
printf("NULL\n");


fnReversePrint(pstruStart);

return 0;

}

INPUT:

enter the number of nodes: 5
enter the data: 10
enter the data: 20
enter the data: 30
enter the data: 40
enter the data: 50

OUTPUT:
the linked list is
10----->20----->30----->40----->50----->NULL
NULL-->50-->40-->30-->20-->10

No comments:

Post a Comment