Data Structures in C
Data Structures in C
Linked List:
Linear DS
elements can stored as per memory availability
can access elements on linear
store homogenous elements(similar)
dynamic in size
easy insertion and deletion
starting element or node is the key termed as head
If head node is lost, linked list is lost
allocate memory with malloc function
Stack:
linear ds
follows LIFO (Last in first out)
only top elements is available to accessed
insertion and deletion takes place from top
major opr:
push()- used insert element
pop() - removes the top element from stack
isEmpty()-returns true is stack empty
peek()-to get the top element of stack
all opr are works in const time eg: O(1)
Demonstration of stack:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
//skeleton of stack
strctStack{
int top;
unsigned size;
int*arr;
//create stack
structStack*create(unsigned size)
{
structStack*stack=(structStack*)malloc(sizeof(structStack));
stack->size=size;
stack->top=-1
stack->arr=(int*)malloc(stack->size*sizeof(int));
returnstack;
}
int isFull(structStack*stack)
{
return stack->top==stack->size -1
}
Queue:
linear ds
follows FIFO: First in first out
insertion can takes places from rear end
deletion takes place from front end
major opr:
enqueue(ele)-used to insert element at top
dequeue()-removes top element
peekfirst()-to get the first element of queue
peeklast()-to get the last element of queue
all opr works in cost time eg: o(1)
DEMONSTRATION OF QUEUE:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
//skeleton of queue
structQueue
{
int front,rear,size;
unsigned capacity;
int* array;
}
//to create a queue
structQueue*createQueue(unsigned capacity)
{
struct Queue*queue=(struct Queue*)malloc(sizeof(structQueue);
queue->capacity=capacity
queue->front=queue->size=0
queue->rear=capacity-1
queue->array=(int*)malloc(queue->capacity*sizeof(int));
return queue;
}
Binary Tree:
hierarchical ds
topmost element is known as the root of tree
every node can have at most 2 children in tree
can access elements randomly using index
common traversal methods:
preorder(root):print-left-right
postorder(root):left-right-print
inorder(root):left-print-right
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
//skeleton of tree
struct node
{
int data;
struct node*left;
struct node*right;
}
DEMONSTRATION OF BST:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int key;
struct node *left, *right;
}
Heap:
Hash:
uses special hash function
hash function maps element to a address for storage
this provide const time access
collision is handled by collision resolution techniques
Collision - try to map more than one element in particular location
collision resolution technique:
chaining
open addressing