Originally Posted by
recluse
could you suggest another print function to reverse the elements in my list? i know my code is dodgy but i just want to get it working. can anyone suggest better code to perform what i'm trying to do.
if you want to print the list backwards,you can use recursions
Code:
#include<stdio.h>
#include<conio.h>
struct node
{
int num;
struct node *next;
};
void print(struct node * first)
{
if(first->next==NULL)
{
printf("%d",first->num);
return;
}
print(first->next);
printf("%d",first->num);
}
int main()
{
struct node *head,*current;
int first=0;
char in='y';
clrscr();
printf("do u wanna enter a no.");
scanf("%c",&in);
while(in=='y')
{
if(first==0)
{
head=malloc(sizeof(struct node));
current=head;
printf("enter the no.");
scanf("%d",&head->num);
first=first+1;
}
else
{
current->next=malloc(sizeof(struct node));
printf("enter the no.");
scanf("%d",¤t->next->num);
current=current->next;
}
printf("do u wanna enter a no.");
scanf("%c",&in);
}
current->next=NULL;
print(head);
getch();
return 0;
}
i think this should work if you want to take in numbers and then print them backwards using the linked list.
be sure to clear the input buffer before each scanf()
ciao