SINGLY LINKED LIST (without functions):
Important Things to remember:
1. Create a structure containing a integer value and a pointer (*), which
points to the structure that we have created.
2. Structure always ends with semicolon (;)
3. Create *head, this pointer is going to point the very first node of the
linked list. Initialize this pointer by NULL.
4. For addding new node into Linked List:
a) Check if head==NULL, if it is NULL, allocate memory of the size of
struct node (here the memory will be 4 bytes) from heap, and make the
head to point to that allocated memory. else go to b)
b) if head!=NULL, traverse the linked list till the last node of it, after
that create a temp node, attach the node at the end of the linked list.
Memory Allocation:
1. Use a function malloc for allocating the memory from the heap area.
2. The function prototype is
void *malloc(size_t size);
3. Return type of the function is void*, which is also called as generic
pointer.
4. The speciality of void* is, it can be typecasted into any other type of
pointer, such as int*, chat*, float* and in this program we have
typecasted it into struct node*.
As it can be typecasted into any other type of pointers, it is called as
"generic pointer".
5. Malloc function accepts one argument, that argument tells malloc, how much
memory it has to allocate from the heap area.
6. In this program, we used sizeof() operator for calculating the size memory
that malloc is going to allocate dynamically.
7. The important thing about the sizeof() is that, eventhough it looks like
a function, but it is not a function, it is an "Operator".
****************************************************************************/
#include
#include
#include
#include
struct node
{
int data;
struct node*next; //this pointer is pointing to the struct node
};
void main()
{
struct node*head=NULL,*trav,*temp;
int choice;
clrscr();
while(1)
{
printf("\n1.Add");
printf("\n2.Display");
printf("\n3.Exit");
printf("\nEnter your choice ");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(head==NULL)
{
head=(struct node*)malloc(sizeof(node));
printf("\nEnter the data ");
scanf("%d",&head->data);
head->next=NULL;
}
else
{
trav=head;
while(trav->next!=NULL)
{
trav=trav->next;
}
temp=(struct node*)malloc(sizeof(node));
printf("\nEnter the data ");
scanf("%d",&temp->data);
temp->next=NULL;
trav->next=temp;
}
break;
case 2:
printf("\n");
for(trav=head;trav!=NULL;trav=trav->next)
{
printf("[%d]->",trav->data);
}
break;
case 3:
exit(0);
}
}
}
/*****************************************************************************
Done By: Prof. Dhumane A.V
*****************************************************************************/
No comments:
Post a Comment