Jun 20, 2011 at 7:14pm UTC
Please explain me the logic behind linked lists and how to insert at head and end?. I have spend at least 3 days on this and still i have been unable to grasp it. Please have a look at the program .
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct student /* declaring the structure */
{
char name[25];
int rollno;
struct student *next; /* the pointer which would be pointing to next node*/
struct student *first;
};
struct student *head=NULL;
struct student * create(void) */ Creates a new object /*
{
struct student *o;
o=(struct student *)malloc(sizeof(struct student));
return o;
}
void read(struct student *ptr)
{
printf("Please enter name and age\n");
gets(&ptr->name[0]);
scanf("%d",&ptr->rollno);
}
void display(struct student *ptr)
{
puts(&ptr->name[0]);
printf("%d\n",ptr->rollno);
}
void insathead(struct student *cur)
{
if(head==NULL)
{
head=cur;
cur->next=NULL;
}
else
{
struct student *first;
first=head;
head=cur;
cur->next=first;
}
}
struct student * last()
{
struct student *p;
p=head;
while(p->next!=NULL)
{
p=p->next;
}
return p;
}
struct student * dispall(void)
{
struct student *p;
p=head;
while(p!=NULL)
{
display(p);
p=p->next;
printf("%d",p);
}
return p;
}
void main()
{
struct student *h;
int ch;
h=create();
read(h);
display(h);
while(1)
{
printf("1 : insert at head\n");
printf("2 : insert at end\n");
printf("3 : display all\n");
printf("4 : Exit\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
insathead(h);
break;
case 3:
dispall();
break;
}
}
}