Wednesday, November 4, 2009

Chap10D[h] Creating link list(inserting from front)

Linked list is a very common data structure often used to store similar data in memory. While the elements of an array occupy contiguous memory locations, those of a linked list are not constrained to be stored in adjacent location. The individual elements are stored “somewhere” in memory, rather like a family dispersed, but still bound together. The order of the elements is maintained by explicit links between them. Thus, a linked list is a collection of elements called nodes, each of which stores two item of information—an element of the list, and a link, i.e., a pointer or an address that indicates explicitly the location of the node containing the successor of this list element. Write a program to build a linked list by adding new nodes at the beginning, at the end or in the middle of the linked list. Also write a function display( ) which display all the nodes present in the linked list.

Reference: http://en.wikipedia.org/wiki/Malloc
http://cslibrary.stanford.edu/103/LinkedListBasics.pdf


#include alloc.h (include arrows)
struct list
{
int x;
struct list *next;
};

void main()
{
struct list *newlist();
struct list *a1=newlist();
struct list *current;
int i,k;
char j[1];


for(i=1,current=a1;current!=NULL;current=current->next,i++)
{
printf("\nThe No. %d in the list is %d",i,current->x);
}


while(1)
{
printf("\nEnter a value to key into the No. %d list",i);
scanf("%d",&k);
push(&a1,k);
printf("\nKey q to quit or any other key to continue keying");
scanf("%s",j);
if(j[0]==113)
break;
}

printf("\nThe new list is as below\n");


for(i=1,current=a1;current!=NULL;current=current->next,i++)
{
printf("\nThe No. %d in the list is %d",i,current->x);
}





}

struct list *newlist()
{
struct list *a1;
struct list *a2;
struct list *a3;

a1=malloc(sizeof(struct list));
a2=malloc(sizeof(struct list));
a3=malloc(sizeof(struct list));

a1->x=1;
a1->next=a2;

a2->x=2;
a2->next=a3;

a3->x=3;
a3->next=NULL;

return(a1);
}

push(struct list **head,int g)
{
struct list *nod=malloc(sizeof(struct list));
nod->x=g;
nod->next=*head;
*head=nod;

}

No comments:

Post a Comment