Singly Linked List & Dynamic Memory in C
Singly Linked List & Dynamic Memory in C
malloc()
It is used to allocate a block of memory of specified size dynamically.
The prototype for the malloc() function is defined in <stdlib.h>
Syntax:
void * malloc(int);
or
ptr = (casttype *)malloc(int);
It receives one argument which indicates the no. of bytes of memory to
be allocated.
On success, it returns a void pointer to the first byte of the memory
allocated.
On failure, it returns NULL.
It is usually used to allocate memory for dynamic data structures
such as Linked lists, trees etc.
Example: int *p;
p = (int*)malloc(8); // allocates 8 bytes of memory
p = (int *)malloc(5*sizeof(int)); // allocates 20 bytes of memory
printf(“\n%f + %f = %f ”,*n1,*n2,*n1+*n2);
free(n1);
free(n2);
return 0;
}
if(p == NULL)
{
printf(“\nInsufficient Memory”);
exit(0);
}
printf(“\nSum = %d”,sum);
free(p);
return 0;
}
struct Book
{
char author[20];
char title[20];
int pages;
float price;
};
int main()
{
struct Book *b;
b = (struct Book*)malloc(sizeof(struct Book));
if(b == NULL)
{
printf(“\nInsufficient Memory”);
exit(0);
}
int main()
{
struct Student *s;
int i,n;
printf(“\nEnter the number of students: “);
scanf(“%d”,&n);
s = (struct Student*)malloc(n*sizeof(struct Student));
if(s == NULL)
{
printf(“\nInsufficient Memory”);
exit(0);
}
printf(“\nEnter the details of %d students……\n”);
for(i=0;i<n;i++)
{
printf(“Enter name, USN, branch and percentage of student%d:\n”,i+1);
scanf(“%s%s%s%f”,s[i].name,s[i].USN,s[i].branch,&s[i].percent);
}
free()
It is used to free the memory allocated dynamically using malloc(),
calloc() or realloc() functions.
The prototype for the free() function is defined in <stdlib.h>
Syntax:
void free(void *);
It receives one argument which is a pointer to the first byte of the
memory allocated dynamically.
It doesn’t return any value.
Once the memory is freed using free(), the pointer becomes a dangling
pointer.
Example: int *p;
p = (int*)malloc(8); // allocates 8 bytes of memory
free(p);
p=NULL;
calloc()
It is used to allocate multiple blocks of memory with each block of
same size dynamically and initialize each byte to zero.
The prototype for the calloc() function is defined in <stdlib.h>
Syntax:
void * calloc(int,int);
or
ptr = (casttype *)calloc(int,int);
It receives two arguments, first argument indicates the no. of blocks
and second argument indicates the size of each block.
On success, it returns a void pointer to the first byte of the memory
allocated.
On failure, it returns NULL.
It is usually used to allocate memory for dynamic data structures
such as dynamic arrays etc.
Example:
int *p;
p = (int *)calloc(5,sizeof(int)); // allocates 20 bytes of memory
if(p == NULL)
{
printf(“\nInsufficient Memory”);
exit(0);
}
large = p[0];
for(i=1;i<n;i++)
{
if(p[i] > large)
large = p[i];
}
printf(“\nLargest number = %d”,large);
free(p);
return 0;
}
str2 = (char*)calloc(i+1,sizeof(char));
if(str2 == NULL)
{
printf(“\nInsufficient Memory”);
exit(0);
}
for(i=0;str1[i]!=‘\0’;i++)
str2[i] =str1[i];
str2[i] = ‘\0’;
printf(“\nOriginal string: %s”,str1);
printf(“\nResultant string: %s”,str2);
free(str2);
return 0;
}
malloc() calloc()
Allocates a single block of Allocates multiple blocks of
memory of specified size. memory with each block of
same size.
It receives one argument. It receives two arguments.
ptr = (casttype*)malloc(int); ptr = (casttype*)calloc(int,int);
Allocated memory space is Allocated memory space is
uninitialized. initialized to zero.
Faster execution Slower execution.
Best suitable for data Best suitable for data
structures such as Linked structures such as dynamic
lists, trees etc. arrays etc.
realloc()
It is used to resize the memory allocated dynamically using malloc() or
calloc().
The prototype for the realloc() function is defined in <stdlib.h>
Syntax:
void * realloc(void*,int);
or
ptr = (casttype *)realloc(ptr,int);
It receives two arguments, first argument is the pointer to the old
memory block and second argument is the new size in bytes.
On success, it returns a void pointer to the first byte of the memory
allocated.
On failure, it returns NULL.
Example1:
int *p;
p = (int *)malloc(10); // allocates 10 bytes of memory
p = (int*)realloc(p,2); //releases 8 bytes of memory
If the new size specified in realloc() is smaller than the size of the old
memory block , then realloc() releases extra bytes of memory allocated
and returns the same pointer.
Example2:
int *p;
p = (int *)malloc(10); // allocates 10 bytes of memory
p = (int*)realloc(p,20); //allocates additional 10 bytes of memory
If the new size specified is larger than the size of the old memory block
then realloc() does one of the following:
If it is possible to extend the memory block then realloc()
extends the memory and returns the same pointer.
If it is not possible to extend then realloc() allocates entirely a
new block, copies the contents of old block to new block,
releases the old block and returns the pointer to the new
memory block.
If it is not possible to allocate the specified amount of memory
then realloc() returns NULL pointer.
str = (char*)malloc(4*sizeof(char));
strcpy(str,”SIT”);
printf(“\nOriginal string: %s”,str);
str = (char*)realloc(str,35);
free(str);
return 0;
}
a = (int*)calloc(n,sizeof(int));
b = (int*)calloc(n,sizeof(int));
c = (int*)calloc(n,sizeof(int));
b = (int*)realloc(b,j*sizeof(int));
c = (int*)realloc(c,k*sizeof(int));
free(a);
free(b);
free(c);
return 0;
}
LINKED LISTS
newnode->info = data;
newnode->next = NULL
if(first == NULL)
first = newnode;
else
{
temp = first;
while(temp->next!=NULL)
temp = temp->next;
temp->next = newnode;
}
printf(“\nNode with info %d is inserted as last node in the list”,data);
return(first);
}
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *next;
}NODE;
newnode->info = data;
newnode->next = NULL;
if(first == NULL)
first = newnode;
else
{
temp = first;
while(temp->next!=NULL)
temp = temp->next;
temp->next = newnode;
}
printf(“\nNode with info %d is inserted as last node in the list”,data);
return(first);
}
temp = first;
first = first->next;
printf(“\nFirst node with info %d is deleted”,temp->info);
free(temp);
}
return(first);
}
printf(“\nListContents:\nBegin->”);
while(first!=NULL)
{
printf(“%d->”,first->info);
first = first ->next;
}
printf(“End”);
}
int main()
{
NODE *first=NULL;
int choice,data;
while(1)
{
printf(“\n\n1:Ins@first\n2:Ins@last\n3:Del@first\n4:Del@last\n5:Display\n6:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the data to be inserted: “);
scanf(“%d”,&data);
first = ins_first(first,data);
break;
first = ins_last(first,data);
break;
case 5: display(first);
break;
case 6: exit(0);
default: printf(“\nInvalid choice”);
}
}
return 0;
}
//ins_first() function
NODE * ins_first(NODE *first,int data)
{
NODE *newnode;
newnode = (NODE*)malloc(sizeof(NODE));
newnode->info = data;
newnode->next = first;
printf(“\n%d is pushed on to the stack”,data);
return(newnode);
}
//del_first() function
NODE * del_first(NODE *first)
{
NODE *temp;
if(first == NULL)
printf(“\nStack underflow”);
else
{
temp = first;
first = first->next;
printf(“\n%d is popped from the stack”,temp->info);
free(temp);
}
return(first);
}
//display() function
void display(NODE *first)
{
if(first == NULL)
{
printf(“\nEmpty Stack”);
return;
}
printf(“\nStack Contents:\nTop->”);
while(first!=NULL)
{
printf(“%d->”,first->info);
first = first ->next;
}
printf(“Bottom”);
}
int main()
{
NODE *first=NULL;
int choice,data;
while(1)
{
printf(“\n\n1:PUSH\n2:POP\n3:Display\n4:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the data to be pushed: “);
scanf(“%d”,&data);
first = ins_first(first,data);
break;
case 3: display(first);
break;
case 4: exit(0);
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *next;
}NODE;
//ins_last() function
NODE * ins_last(NODE *first,int data)
{
NODE *newnode,*temp;
newnode = (NODE*)malloc(sizeof(NODE));
newnode->info = data;
newnode->next = NULL;
if(first == NULL)
first=newnode;
else
{
temp = first;
while(temp->next!=NULL)
temp = temp->next;
temp->next = newnode;
}
printf(“\n%d is inserted into Queue”,data);
return(first);
}
//del_first() function
NODE * del_first(NODE *first)
{
NODE *temp;
if(first == NULL)
printf(“\nQueue underflow”);
else
{
temp = first;
first = first->next;
printf(“\n%d is deleted from the queue”,temp->info);
free(temp);
}
return(first);
}
//display() function
void display(NODE *first)
{
if(first == NULL)
{
printf(“\nEmpty Queue”);
return;
}
printf(“\nQueue Contents:\nFront->”);
while(first!=NULL)
{
printf(“%d->”,first->info);
first = first ->next;
}
printf(“Rear”);
}
int main()
{
NODE *first=NULL;
int choice,data;
while(1)
{
printf(“\n\n1:Insert\n2:Delete\n3:Display\n4:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the data to be inserted: “);
scanf(“%d”,&data);
first = ins_last(first,data);
break;
case 3: display(first);
break;
case 4: exit(0);
if(first == NULL)
printf("\nFailure, Node with key %d is not found”,key);
else
printf(“\nSuccess, Node with key %d is found”,key);
}
}
C Function to display the info of the nodes whose value is in the range
100-200 in a SLL.
if(first==NULL)
first=newnode;
else
{
temp=first;
while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
printf("\nPlayer %s is added at the end of the list",newnode->player);
return first;
}
if(first==NULL)
printf("\nEmpty list");
else
{
printf("\nEnter the player name to search: ");
scanf("%s",player);
temp=first;
while(temp!=NULL && strcmp(temp->player,player)!=0)
temp=temp->next;
if(temp==NULL)
printf("\nPlayer %s not existing in the list",player);
else
{
printf("\nPlayer %s is existing in the list",player);
printf("\nCurrent batting average: %f",temp->bavg);
return first;
}
int main()
{
NODE *first=NULL;
int choice;
while(1)
{
printf("\n1:ADD PLAYER\n2:SEARCH PLAYER\n3:DISPLAY PLAYER\n4:EXIT");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: first=addPlayer(first);
break;
case 2: first=searchPlayer(first);
break;
case 3: display(first);
break;
case 4: exit(0);
return 0;
}
while(cf!=999)
{
printf("\nEnter power of x: ");
scanf("%f",&px);
printf("\nEnter power of y: ");
scanf("%f",&py);
first=ins_last(first,cf,px,py);
while(first->next!=NULL)
{
printf("%.0f x^%.0f y^%.0f + ",first->coeff,first->powx,first->powy);
first = first->next;
}
printf("%.0f x^%.0f y^%.0f ",first->coeff,first->powx,first->powy);
}
if(cf!=0)
p3=ins_last(p3,cf,p1->powx,p1->powy);
}
p2=temp;
p1=p1->next;
}
while(p2!=NULL)
{
if(p2->flag==0)
p3 = ins_last(p3,p2->coeff,p2->powx,p2->powy);
p2=p2->next;
}
return p3;
}
int main()
{
NODE *p1=NULL,*p2=NULL,*p3=NULL;
p3 = add_p(p1,p2,p3);
printf("\n\nFirst polynomial:\n");
display(p1);
printf("\n\nSecond polynomial:\n");
display(p2);
printf("\n\nResultant polynomial:\n");
display(p3);
return 0;
}
Ordered List
A list in which the elements are arranged in some order is referred to as an
ordered list.
else
{
temp = first;
while(temp!=NULL && data>temp->info)
{
prev = temp;
temp = temp->next;
}
if(temp == NULL || data != temp->info)
{
prev->next = newnode;
newnode->next = temp;
}
}
return first;
}
newnode = (NODE*)malloc(sizeof(NODE));
newnode->info = data;
prev->next = newnode;
newnode->next = temp;
}
printf(“\n%d is inserted into the queue”, data);
return first;
}
int main()
{
NODE *first=NULL;
int choice,data;
while(1)
{
printf(“\n\n1:Insert\n2:Delete\n3:Display\n4:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the data to be inserted: “);
scanf(“%d”,&data);
first = Insert(first,data);
break;
case 3: display(first);
break;
case 4: exit(0);
default: printf(“\nInvalid choice”);
}
}
return 0;
}
L2 = L2->next;
}
}
while(L1!=NULL)
{
L3 = ins_last(L3,L1->info);
L1 = L1->next;
}
while(L2!=NULL)
{
L3 = ins_last(L3,L2->info);
L2 = L2->next;
}
return(L3);
}
return(L3);
}
Solution:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
if(first==NULL || data<first->info)
{
newnode->next=first;
first=newnode;
}
else
{
temp=first;
if(temp==NULL || data!=temp->info)
{
prev->next=newnode;
newnode->next=temp;
}
}
return first;
}
newnode->info = data;
newnode->next = NULL;
if(first == NULL)
first = newnode;
else
{
temp = first;
while(temp->next!=NULL)
temp = temp->next;
temp->next = newnode;
}
printf(“\nNode with info %d is inserted as last node in the list”,data);
return(first);
}
printf("Contents:\nBegin->");
while(first!=NULL)
{
printf("%d->",first->info);
first=first->next;
}
printf("End");
}
while(L1!=NULL)
{
L3 = ins_last(L3,L1->info);
L1 = L1->next;
}
while(L2!=NULL)
{
L3 = ins_last(L3,L2->info);
L2 = L2->next;
}
return L3;
}
int main()
{
NODE *L1=NULL,*L2=NULL,*L3=NULL;
int data,choice;
while(1)
{
printf("\n\n1:INS_LIST1\n2:INS_LIST2\n3:MERGE\n4:DISPLAY\n5:EXIT");
printf("\nEnter your choice: ");
scanf("%d",&choice);
switch(choice)
{
case 1: printf("\nEnter the data: ");
scanf("%d",&data);
L1 = insert(L1,data);
break;
L2 = insert(L2,data);
break;
case 3: L3=merge(L1,L2);
printf("\nList3 ");
display(L3);
break;
printf("\nList2 ");
display(L2);
break;
case 5: exit(0);
default:printf("\nInvalid choice");
}
}
return 0;
}
Header Node
It is a special extra node present at the front of the list which is used
to store some global information about the list. It doesn’t represent the
data item of the list.
Advantage:
Using header node simplifies operations such as inserting at the end
of the list, deleting the last node etc.
Diagrammatic Representation
newnode->info = data;
newnode->next = NULL;
temp = head;
while(temp->next!=NULL)
temp = temp->next;
temp->next = newnode;
head->info++;
printf(“\nNode with info %d is inserted as last node in the list”,data);
}
prev = temp;
temp = temp->next;
}
prev->next = NULL;
printf(“\nLast Node with info %d is deleted”,temp->info);
head->info--;
free(temp);
}
newnode->next = head->next;
head->next = newnode;
head->info++;
printf(“\nNode with info %d is inserted as first node in the list”,data);
}
prev->next = NULL;
printf(“\nLast Node with info %d is deleted”,temp->info);
head->info--;
free(temp);
}
int main()
{
NODE *head;
int choice,data;
head = (NODE*)malloc(sizeof(NODE));
head->info = 0;
head->next = NULL;
while(1)
{
printf(“\n\n1:Ins@first\n2:Ins@last\n3:Del@first\n4:Del@last\n5:Display\n6:Exit”);
printf(“\nEnter your choice: “);
scanf(“%d”,&choice);
switch(choice)
{
case 1: printf(“\nEnter the data to be inserted: “);
scanf(“%d”,&data);
ins_first(head,data);
break;
ins_last(head,data);
break;
case 3: del_first(head);
break;
case 4: del_last(head);
break;
case 5: display(head);
break;
case 6: exit(0);
return 0;
}