Data Structure
Data Structure
Data Structure
The stack is a place in the computer memory where all the variables that are declared and initialized
before runtime are stored. The heap is the section of computer memory where all the variables created
or initialized at runtime are stored.
What is stack?
The two sections other from the code segment in the memory are used for data. The stack is the section
of memory that is allocated for automatic variables within functions.
Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the
memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is
a section of memory and its associated registers that is used for temporary storage of information in
which the most recently stored item is the first to be retrieved.
What is heap?
On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of
memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of
blocks is not known until run time. Heap is usually being used by a program for many different
purposes.
The stack is much faster than the heap but also smaller and more expensive.
When a program begins executing in the main() function, all variables declared within main() will be
stored on the stack.
If the main() function calls another function in the program, for example calcSize(), additional
storage will be allocated for the variables in calcSize(). This storage will be allocated in the heap
memory segment.
Notice that the parameters passed by main() to calcSize() are also stored on the stack. If the
calcSize() function calls to any additional functions, more space would be allocated at the heap
again.
When the calcSize() function returns the value, the space for its local variables at heap is then
deallocated and heap clears to be available for other functions.
The memory allocated in the heap area is used and reused during program execution.
It should be noted that memory allocated in heap will contain garbage values left over from previous
usage.
Memory space for objects is always allocated in heap. Objects are placed on the heap.
Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.
Even though objects are held on heap, references to them are also variables and they are placed on
stack.
The stack segment provides more stable storage of data for a program. The memory allocated in
the stack remains in existence for the duration of a program. This is good for global and static
variables. Therefore, global variables and static variables are allocated on the stack.
Why is stack and heap important?
When a program is loaded into memory, it takes some memory management to organize the process. If
memory management was not present in your computer memory, programs would clash with each
other leaving the computer non-functional.
IT
Programming
FROM:
your email here
2+6-3=
Send
Data Structure in C
A memory play a vital role in c because all variable you declare are at first stored in the memory. Some
memory allocation is done at compile time and some at runtime. Memory which is allocated and de-
allocated during the execution of the program is known as dynamic memory. Memory span and shrink
as per application requirement and this is one of major advantage of pointer.
A memory can be categories in following segments
Text Segment
Data Segment
Free Space
Stack Segment
Data Segment in sub-categories in two parts
Static Segment
Heap Segment
The Static Segment hold the global variables and the Heap Segment hold the dynamic variable.
Dynamic memory allocation is done by using malloc() funtion in C.
In this tutorial you will learn about Pointer, Linked List, Stacks, Queues, Trees, and Graphs which are
related with the data structures.
Pointer in C
In the previous tutorial you come to know what is data structure, dynamic memory allocation. Now in
this tutorial you will see the how we declare a pointer variable. How it works with a very simple
example.
Array Implementation in C
In this tutorial you will learn how to implement an array in C. There are two function in this given
example one for reading the array element and other for writing on console.
Sum of array element in C
In this tutorial you will know how to get the sum of each element of an array. There are two function in
this given example one for reading the array element and other for writing on console.
Inverse of an array in C
In this tutorial you will know how to inverse an array in c language. There are three function in this
given example one for reading the array element, second for writing on console and last for inverse of
an array.
Stack
The stack is one of the most important data structures in computer science. A stack is a last-in first-out
data structure (LIFO).
Representing Graph using adjacency list & perform DFS & BFS
A graph is a collection of nodes and edges.
Pointer in C
Posted on: April 29, 2010 at 12:00 AM
In the previous tutorial you come to know what is data structure, dynamic memory allocation.
Now in this tutorial you will see the how we declare a pointer variable. How it works with a very
simple example.
About Pointer
A pointer is a variable which contain the memory address. It also points to a specific data types. Three
operator are commonly used when dealing with pointer.
1 & address operator
2 * de-referencing operator
3 -> structure pointer operator
Example:
In this example you will see how pointer works.
In the above figure you see that c is a variable of char data-type and it has value "A" inside. The
address of variable c is 0X3000
Now in this figure you see that c is a variable of char data-type and it has value 'A' inside. The address
variable c is 0X3000. And a pointer variable cptr of char data-type. The cptr pointer variable having the
address of c variable rather value. So this is one the important difference between a general variable
and pointer variable is that a pointer variable contains memory address.
A complete example
#include <stdio.h>
void main()
{
char c ='A';
char *cptr;
cptr=&c;
printf("\nThe address of c is\t%p",&c);
printf("\nValue of c is\t\t%c",c);
printf("\n\nThe address of cptr is\t %p",&cptr);
printf("\nValue of cptr is\t%p",cptr);
printf("\nAccess variable which cptr point to is\t%c",*cptr);
}
Output:
From the output of above example you can see that the address of these two variables are different and
the pointer variable holding the address of another variable which it point to.
Download this code
Related Tags for Pointer in C:
Description:
In this tutorial you will see how pointer is used with structure. This is a very important example
because all data-structure program work on this principle.
Code:
#include <stdio.h>
#include <conio.h>
struct record
{
char name[20];
int roll;
};
struct record r,*p;
void main()
{
p=&r;
clrscr();
printf("\nEnter the name\n");
scanf("\n%s",&p->name);
printf("\nEnter the roll no\n");
scanf("%d",&p->roll);
printf("\n%s",p->name);
printf("\n%d",p->roll);
}
Code Description:
p=&r assign the address of object to p
*p allow the pointer to access the objects
*p.roll is same as p->roll like used in example.
Output:
In the next page you will see a list of program on each above topics.
Related Tags for Linear and Non-Linear Data Structure in C:
In this tutorial you will learn how to implement an array in C. There are two function in this
given example one for reading the array element and other for writing on console.
Array Implementation in C
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
int size[5],i,sum=0;
clrscr();
printf("Enter five elements for an array \n");
read(size,5);
printf("All elements of the array are : \n");
display(size,5);
}
Output:
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
int a[5],i,sum=0;
clrscr();
printf("Enter five elements for an array \n");
read(a,5);
printf("The list elements are \n");
display(a,5);
for(i=0;i<5;i++)
{
sum+=a[i];
}
printf("The sum of the elements of the array is %d\n",sum);
getch();
}
Output:
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void addarray(int * ,int *,int * ,int);
int a[5],b[5],c[5],i;
clrscr();
printf("Enter the elements for first array \n");
read(a,5);
printf("Enter the elements for second array \n");
read(b,5);
addarray(a,b,c,i);
printf("The sum corresponding element of both array is : \n");
display(c,5);
getch();
}
Inverse of an array in C
Posted on: April 30, 2010 at 12:00 AM
In this tutorial you will know how to inverse an array in c language. There are three function in
this given example one for reading the array element, second for writing on console and last for
inverse of an array.
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void inverse(int *,int);
int a[6],i;
clrscr();
read(a,6);
display(a,6);
inverse(a,6);
display(a,6);
getch();
}
Output:
Code:
#include<stdio.h>
#include<conio.h>
void main()
{
void read(int *,int);
void display(int *,int);
void sort(int *,int);
void mergelist(int *,int *,int *,int);
int a[5],b[5],c[10];
clrscr();
printf("Enter the elements for the first array \n");
read(a,5);
printf("The elements of first array are : \n");
display(a,5);
printf("Enter the elements for the second array \n");
read(b,5);
printf("The elements of second array are : \n");
display(b,5);
sort(a,5);
printf("The sorted first array in decending order are :\n");
display(a,5);
sort(b,5);
printf("The sorted second array in decending order are :\n");
display(b,5);
mergelist(a,b,c,5);
printf("The elements of merged list is \n");
display(c,10);
getch();
}
void read(int c[],int i)
{
int j;
for(j=0;j<i;j++)
scanf("%d",&c[j]);
}
}
}
Output:
Linked List
A linked list is a data structure which consists of data record in a sequence such that each data record
have a field of data as well as link reference to its connected node. It do not provide the random access
to any of its member data as it is form of a indexing and the connected node is pre-defined.
In the next page you will see various example with this context.
Related Tags for Overview of Linked List:
Description:
In this example you will see how to create a node and insert data record in singly link list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int num)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = num;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link != NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = num;
temp-> link = NULL;
}
return
(p);
}
void printlist ( struct node *p )
{
printf("The data values of your list are\n");
while (p!= NULL)
{
printf("%d\t",p-> data);
p = p-> link;
}
}
void main()
{
int n;
int x;
struct node *start = NULL ;
printf("Enter number of nodes you want to create \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter data values for each node\n");
scanf("%d",&x);
start = insert ( start , x );
}
printf("The created single link list is\n");
printlist ( start );
}
Output:
if(p==NULL)
{
p=(struct dnode *)malloc(sizeof(struct dnode));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p->data = n;
p-> prev = p->next =NULL;
*q =p;
}
else
{
temp = (struct dnode *)malloc(sizeof(struct dnode));
if(temp == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp->data = n;
temp->prev = (*q);
temp->next = NULL;
(*q)->next = temp;
(*q) = temp;
}
return (p);
}
void main()
{
int n;
int x;
struct dnode *start = NULL ;
struct dnode *end = NULL;
printf("Enter the number of nodes to be created \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data values for each node\n");
scanf("%d",&x);
start = insert ( start , &end,x );
}
printnode( start );
}
Output:
Description:
In the circular linked list the link of lat node is connected to the first node.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int n)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error Occurred\n");
exit(0);
}
p-> data = n;
p-> link = p;
}
else
{
temp = p;
while (temp-> link != p)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error Occurred\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = p;
}
return (p);
}
void printlist ( struct node *p )
{
struct node *temp;
temp = p;
printf("The data in the list are :\n");
if (p!= NULL)
{ do
{
printf("%d\t",temp-> data);
temp=temp->link;
}while(temp!=p);
}
else
printf("The link is empty \n");
}
void main()
{
int num;
int value;
struct node *start = NULL ;
printf("Enter the number of nodes to be created \n");
scanf("%d",&num);
while ( num-- > 0 )
{
printf( "Enter the data to be placed in a node\n");
scanf("%d",&value);
start = insert ( start , value );
}
printlist ( start );
}
This tutorial demonstrate how to count the number of nodes present in the linked list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node * , int);
int countnode(struct node*);
void printlist (struct node *);
void main()
{
int n;
int x;
struct node *start = NULL ;
printf("Enter number of nodes to be created \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for node\n");
scanf("%d",&x);
start = insert ( start ,x);
}
printlist ( start );
n = countnode(start);
printf("\nThe number of nodes in a list are: %d\n",n);
}
Output:
This tutorial demonstrate how to splits the list into two equal size list having same data inside.
Description:
In this example it has mainly three function one for inserting data into list another for printing the list
and last one for split of list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
else
printf("empty list\n");
}
void main()
{
int n,num;
int x;
struct node *start1 = NULL ;
struct node *start2=NULL;
printf("Enter the number of node for each splited list \n");
scanf("%d",&n);
num = n;
n*=2; /* this is done to have data multiple of two
so that it split into two equal parts. */
while ( n-- > 0 )
{
printf( "\nEnter data to be placed in node\n");
scanf("%d",&x);
start1 = insertnode ( start1 , x );
}
printlist ( start1 );
splitlist(start1,&start2,num);
printf("\nFirst list is:\n");
printlist(start1);
printf("\nSecond list is:\n");
printlist(start2);
Output:
Description:
In this example it has mainly three function one for inserting data into list another for printing the list
and last one for split of list.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
else
printf("empty list\n");
}
void main()
{
int n,num;
int x;
struct node *start1 = NULL ;
struct node *start2=NULL;
printf("Enter the number of node for each splited list \n");
scanf("%d",&n);
num = n;
n*=2; /* this is done to have data multiple of two
so that it split into two equal parts. */
while ( n-- > 0 )
{
printf( "\nEnter data to be placed in node\n");
scanf("%d",&x);
start1 = insertnode ( start1 , x );
}
printlist ( start1 );
splitlist(start1,&start2,num);
printf("\nFirst list is:\n");
printlist(start1);
printf("\nSecond list is:\n");
printlist(start2);
Output:
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *mergelist (struct node *, struct node *);
struct node *insertnode(struct node *p , int n)
{
struct node *temp;
if(p==NULL)
{
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Error\n");
exit(0);
}
p-> data = n;
p-> link = NULL;
}
else
{
temp = p;
while (temp-> link!= NULL)
temp = temp-> link;
temp-> link = (struct node *)malloc(sizeof(struct node));
if(temp -> link == NULL)
{
printf("Error\n");
exit(0);
}
temp = temp-> link;
temp-> data = n;
temp-> link = NULL;
}
return (p);
}
void main()
{
int n;
int x;
struct node *start1 = NULL ;
struct node *start2 = NULL;
struct node *start3 = NULL;
printf("Enter the number of nodes for the first list \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for the first node\n");
scanf("%d",&x);
start1 = insertnode ( start1 ,x);
}
printlist ( start1 );
printf("\nEnter the number of nodes for the second list \n");
scanf("%d",&n);
while ( n-- > 0 )
{
printf( "Enter the data for the second node\n");
scanf("%d",&x);
start2 = insertnode ( start2 ,x);
}
printlist ( start2 );
start3 = mergelist(start1,start2);
printf("\nThe merged list is\n");
printlist ( start3);
}
Output:
Stack
Posted on: May 7, 2010 at 12:00 AM
The stack is one of the most important data structures in computer science. A stack is a last-in
first-out data structure (LIFO).
Stack Overview
Stack follows the rule of last in first out rule. Mainly two action are performed by stack one is push and
other is pop. The last thing which we placed or push on stack is the first thing we can get when we pop.
A stack is a list of element with insertion and deletion at one end only.
Below depict the operational behaviors of stack. You can see one thing that push and pop operation is
done at one end and whatever element we keep on stack is shown at the top of stack.
Description:
In this tutorial of data-structure you will see push and pop operation of stack. In the previous tutorial is
clearly explained the push pop operation. The drawback of implementing stack is that the size of stack
is fixed it cannot grow or shrink.
Code:
#include <stdio.h>
#include <stdlib.h>
void push(int stack[], int *top, int value)
{
if(*top < 4 )
{
*top = *top + 1;
stack[*top] = value;
printf("\nStack element should be less than four\n");
}
else
{
printf("\nThe stack is full can not push a value\n");
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("\nThe stack is empty can not pop a value\n");
exit(0);
}
}
void main()
{
int stack[4];
int top = 0;
int n,value;
do
{
do
{
printf("\nEnter the element to be pushed\n");
scanf("%d",&value);
push(stack,&top,value);
printf("\nEnter 1 to continue and other key to pop\n");
scanf("%d",&n);
printf("");
} while(n == 1);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("\nThe value poped is %d",value);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
}
printf("\nEnter 1 to continue and other key to push\n");
scanf("%d",&n);
} while(n == 1);
}
Output:
Related Tags for Stack:
Description:
In this tutorial of data-structure you will see push and pop operation of stack using linked list. In the
previous tutorial the stack operation in done using array.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *push(struct node *p , int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available\n");
exit(0);
}
temp->data = value;
temp->link = p;
p = temp;
return(p);
}
void main()
{
struct node *top = NULL;
int n,value;
do
{
do
{
printf("Enter the element to be pushed in stack\n");
scanf("%d",&value);
top = push(top,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
Output:
Description:
In this tutorial of data-structure you will see push and pop operation of stack. In the previous tutorial is
clearly explained the push pop operation. The drawback of implementing stack is that the size of stack
is fixed it cannot grow or shrink.
Code:
#include <stdio.h>
#include <stdlib.h>
void push(int stack[], int *top, int value)
{
if(*top < 4 )
{
*top = *top + 1;
stack[*top] = value;
printf("\nStack element should be less than four\n");
}
else
{
printf("\nThe stack is full can not push a value\n");
exit(0);
}
}
void pop(int stack[], int *top, int * value)
{
if(*top >= 0 )
{
*value = stack[*top];
*top = *top - 1;
}
else
{
printf("\nThe stack is empty can not pop a value\n");
exit(0);
}
}
void main()
{
int stack[4];
int top = 0;
int n,value;
do
{
do
{
printf("\nEnter the element to be pushed\n");
scanf("%d",&value);
push(stack,&top,value);
printf("\nEnter 1 to continue and other key to pop\n");
scanf("%d",&n);
printf("");
} while(n == 1);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
while( n == 1)
{
pop(stack,&top,&value);
printf("\nThe value poped is %d",value);
printf("\nEnter 1 to pop an element\n");
scanf("%d",&n);
}
printf("\nEnter 1 to continue and other key to push\n");
scanf("%d",&n);
} while(n == 1);
}
Output:
Description:
In this tutorial you will see how to implement queue using array and queue insert & delete operations.
Code:
#include <stdio.h>
#define MAX 5
#include <stdlib.h>
void main()
{
int queue[MAX];
int front,rear;
int n,value;
front=rear=(-1);
do
{
do
{
printf("Enter the element to be inserted in queue\n");
scanf("%d",&value);
insert(queue,&rear,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to delete an element from queue\n");
scanf("%d",&n);
while( n == 1)
{
deleteQ(queue,&front,rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element from queue\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}
Output:
Queue implementation using linked list.
Posted on: June 19, 2010 at 12:00 AM
This tutorial demonstrate how to implement queue using linked list.
Description:
The advantage of using linked list is that there is no size limit. The size of queue grow and shrink as per
insertion and deletion takes place.
Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
void insert(struct node **front, struct node **rear , int value)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
if(temp==NULL)
{
printf("No Memory available\n");
exit(0);
}
temp->data = value;
temp->link=NULL;
if(*rear == NULL)
{
*rear = temp;
*front = *rear;
}
else
{
(*rear)->link = temp;
*rear = temp;
}
}
void main()
{
struct node *front=NULL,*rear = NULL;
int n,value;
do
{
do
{
printf("Enter the element to be inserted\n");
scanf("%d",&value);
insert(&front,&rear,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
while( n == 1)
{
deleteQ(&front,&rear,&value);
printf("The value deleted is %d\n",value);
printf("Enter 1 to delete an element\n");
scanf("%d",&n);
}
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
}
Output
Code:
#include <stdio.h>
#define MAX 5
#include <stdlib.h>
void main()
{
int queue[MAX];
int front,rear;
int n,value;
front=0; rear=0;
do
{
do
{
printf("Enter the element to be inserted\n");
scanf("%d",&value);
insert(queue,&rear,front,value);
printf("Enter 1 to continue\n");
scanf("%d",&n);
} while(n == 1);
Output:
Description:
A tree data structure that are based on hierarchical tree structure with sets of nodes. A tree is a acyclic
connected graph with zero or more children nodes and at most one parent nodes.
Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *lchild, *rchild;
};
while(temp1 != NULL)
{
temp2 = temp1;
if( temp1 ->data > val)
temp1 = temp1->lchild;
else
temp1 = temp1->rchild;
}
if( temp2->data > val)
{
temp2->lchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->lchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
else
{
temp2->rchild = (struct node*)malloc(sizeof(struct node));
temp2 = temp2->rchild;
if(temp2 == NULL)
{
printf("Cannot allocate memory\n");
exit(0);
}
temp2->data = val;
temp2->lchild=temp2->rchild = NULL;
}
}
return(p);
}
Output:
Representing Graph using adjacency list & perform DFS & BFS
Posted on: June 21, 2010 at 12:00 AM
A graph is a collection of nodes and edges.
Description:
This tutorial demonstrate how to create a graph using adjacency list and perform DFS and BFS.
Different kind of graph are listed below:
Directed Graph: A directed graph is one in which edges connect nodes in only one
direction(unidirectional).
Undirected Graph: An undirected graph is one in which edges connect nodes bidirectionally (in both
directions). Node: A node, usually drawn as a circle, represents an item that can be related to other
items or nodes. Nodes are sometimes referred to as vertices.
Edge: An edge represents a connection between nodes. Edges can be either directed or undirected,
depending on the type of graph. Edges can also have weights, which may corresponds distance between
edges.
Connected: A graph is said to be connected if from any node you can reach any other node.
Disconnected: A graph is said to be disconnected if certain groups of nodes from an island that has no
connection to the rest of the graph.
Code:
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
#define max 10
struct node
{
int vertex;
struct node *next;
};
typedef struct node* nodeptr;
typedef struct queue
{
int front,rear;
int arr[max];
};
typedef struct stack
{
int top;
int arr[max];
};
nodeptr getnode()
{
nodeptr p;
p=(nodeptr)malloc(sizeof(struct node));
p->next=NULL;
return p;
}
do
{
printf("\n Enter The Edge Between Two Vertices:\t");
scanf("%d%d",&v1,&v2);
new1=getnode();
new1->vertex=v2;
p=head[v1];
if(p==NULL)
head[v1]=new1;
else
{
while(p->next!=NULL)
p=p->next;
p->next=new1;
}
if(c==1)
{
new1=getnode();
new1->vertex=v1;
p=head[v2];
if(p==NULL)
head[v2]=new1;
else
{
while(p->next!=NULL)
p=p->next;
p->next=new1;
}
}
printf("\n Do You Want To Add More Edges In Graph(y/n):\t");
ch=getche();
}while(ch=='y'||ch=='Y');
}
}while(!empty(&s));
}
void BFS(nodeptr head[],int start,int visited[])
{
nodeptr adj;
struct queue q;
int v;
q.front=0;
q.rear=-1;
visited[start]=1;
printf("\n %d",start);
insertq(&q,start);
while(!qempty(&q))
{
v=removeq(&q);
adj=head[v];
while(adj!=NULL)
{
if(visited[adj->vertex]==0)
{
visited[adj->vertex]=1;
printf("\t %d",adj->vertex);
}
adj=adj->next;
}
}
}
void main()
{
char c='y';
int ch,start,n,visited[10];
nodeptr head[10];
clrscr();
do
{
clrscr();
printf("\n========Graph========");
printf("\n 1. Create");
printf("\n 2. Display Adjancency List");
printf("\n 3. Depth First Search(Rec)");
printf("\n 4. Depth First Search(Non-Rec)");
printf("\n 5. Breadth First Search");
printf("\n 6. Exit");
printf("\n=====================");
printf("\n Enter Your Choice:\t");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter The No. of Vertices In Graph:\t");
scanf("%d",&n);
init(head,n);
create(head);
break;
case 2:
display(head,n);
break;
case 3:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
printf("\n Recursive Depth First Search Is\n");
DFSR(head,start,visited);
break;
case 4:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
printf("\n Non-Recursive Depth First Search Is\n");
DFSN(head,start,visited);
break;
case 5:
printf("\n Enter The Vertex From Which You Want To Start Traversal");
scanf("%d",&start);
initialise_visit(visited,n);
BFS(head,start,visited);
break;
case 6:
break;
}
printf("\n Do You Want To Continue(y/n):\t");
c=getche();
}while(c=='Y'||c=='y');
getch();
}
Output:
What is stack?
The two sections other from the code segment in the memory are used for data. The stack is the section
of memory that is allocated for automatic variables within functions.
Data is stored in stack using the Last In First Out (LIFO) method. This means that storage in the
memory is allocated and deallocated at only one end of the memory called the top of the stack. Stack is
a section of memory and its associated registers that is used for temporary storage of information in
which the most recently stored item is the first to be retrieved.
What is heap?
On the other hand, heap is an area of memory used for dynamic memory allocation. Blocks of
memory are allocated and freed in this case in an arbitrary order. The pattern of allocation and size of
blocks is not known until run time. Heap is usually being used by a program for many different
purposes.
The stack is much faster than the heap but also smaller and more expensive.
Heap and stack from programming perspective
Most object-oriented languages have some defined structure, and some come with so-called main()
function. When a program begins running, the system calls the function main() which marks the
entry point of the program. For example every C, C++, or C# program must have one function named
main(). No other function in the program can be called main(). Before we start explaining, let's
take a look at the following example:
int x; /* static stack storage */
void main() {
int y; /* dynamic stack storage */
char str; /* dynamic stack storage */
str = malloc(50); /* allocates 50 bytes of dynamic heap storage */
size = calcSize(10); /* dynamic heap storage */
When a program begins executing in the main() function, all variables declared within main() will be
stored on the stack.
If the main() function calls another function in the program, for example calcSize(), additional
storage will be allocated for the variables in calcSize(). This storage will be allocated in the heap
memory segment.
Notice that the parameters passed by main() to calcSize() are also stored on the stack. If the
calcSize() function calls to any additional functions, more space would be allocated at the heap
again.
When the calcSize() function returns the value, the space for its local variables at heap is then
deallocated and heap clears to be available for other functions.
The memory allocated in the heap area is used and reused during program execution.
It should be noted that memory allocated in heap will contain garbage values left over from previous
usage.
Memory space for objects is always allocated in heap. Objects are placed on the heap.
Built-in datatypes like int, double, float and parameters to methods are allocated on the stack.
Even though objects are held on heap, references to them are also variables and they are placed on
stack.
The stack segment provides more stable storage of data for a program. The memory allocated in
the stack remains in existence for the duration of a program. This is good for global and static
variables. Therefore, global variables and static variables are allocated on the stack.
IT
Programming
FROM:
your email here
2+6-3=
Send