You are on page 1of 54

Data structures and algorithms:

Assignment-2:
1)Code to insert a node at the beginning of list using C language:
#include <stdio.h>
#include <stdlib.h>

struct node
{
int num;
struct node *nextptr;
}*stnode;

void createNodeList(int n);


void NodeInsertatBegin(int num);
void displayList();

int main()
{
int n,num;
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list are : \n");
displayList();
printf("\n Input data to insert at the beginning of the list : ");
scanf("%d", &num);
NodeInsertatBegin(num);
printf("\n Data after inserted in the list are : \n");
displayList();
return 0;
}
void createNodeList(int n)
{
struct node *fnNode, *tmp;
int num, i;

stnode = (struct node *)malloc(sizeof(struct node));


if(stnode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode-> num = num;
stnode-> nextptr = NULL;
tmp = stnode;

for(i=2; i<=n; i++)


{
fnNode = (struct node *)malloc(sizeof(struct node));

if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
break;
}
else
{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num;
fnNode->nextptr = NULL;
tmp->nextptr = fnNode;
tmp = tmp->nextptr;
}
}
}
}

void NodeInsertatBegin(int num)


{
struct node *fnNode;
fnNode = (struct node*)malloc(sizeof(struct node));
if(fnNode == NULL)
{
printf(" Memory can not be allocated.");
}
else
{
fnNode->num = num;
fnNode->nextptr = stnode;
stnode = fnNode;
}
}

void displayList()
{
struct node *tmp;
if(stnode == NULL)
{
printf(" No data found in the list.");
}
else
{
tmp = stnode;
while(tmp != NULL)
{
printf(" Data = %d\n", tmp->num);
tmp = tmp->nextptr;
}
}
}
2)Code to delete occurrences in a singly linked list using C language:
#include <stdio.h>
#include <stdlib.h>

// A linked list node


typedef struct Node {
int data;
struct Node* next;
} Node;

void push(struct Node** head_ref, int new_data)


{
struct Node* new_node
= (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
Node* deleteKey(Node* head, int x)
{
if (!head)
return head;

while (head && head->data == x)


head = head->next;
Node *curr = head, *prev = NULL;
while (curr) {
if (curr->data == x)
prev->next = curr->next;
else
prev = curr;
curr = curr->next;
}
return head;
}

void printList(Node* node)


{
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}

int main()
{

struct Node* head = NULL;

push(&head, 1);
push(&head, 5);
push(&head, 3);
push(&head, 5);
push(&head, 8);
push(&head, 1);
push(&head, 5);
push(&head, 5);

int key = 5;

puts("Created Linked List: ");


printList(head);

// Function call
head = deleteKey(head, key);
if (!head)
printf("\nNo element present in the Linked list\n");
else {
printf("\nLinked List after Deletion is:\n");
printList(head);
}
return 0;
}
3)Code to delete a value from a doubly linked list in C language:
#include <stdio.h>
#include <stdlib.h>

struct Node
{
int data;
struct Node* next;
struct Node* prev;
};

void deleteNode(struct Node** head_ref,


struct Node* del)
{

if (*head_ref == NULL || del == NULL)


return;

if (*head_ref == del)
*head_ref = del->next;

if (del->next != NULL)
del->next->prev = del->prev;

if (del->prev != NULL)
del->prev->next = del->next;

free(del);
return;
}

void push(struct Node** head_ref,


int new_data)
{

struct Node* new_node =


(struct Node*)malloc(sizeof(struct Node));

new_node->data = new_data;

new_node->prev = NULL;

new_node->next = (*head_ref);

if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;

(*head_ref) = new_node;
}

void printList(struct Node* node)


{
while (node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
}

int main()
{

struct Node* head = NULL;

push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);

printf(
"Original Linked list\n ");
printList(head);

deleteNode(&head, head);

deleteNode(&head, head->next);

deleteNode(&head, head->next);

printf("\nModified Linked list\n");


printList(head);
getchar();
}

4)Code to insert in a circular linked list in C language:


#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node * next;
}*head;

void createList(int n);


void displayList();
void insertAtBeginning(int data);
void insertAtN(int data, int position);

int main()
{
int n, data, choice=1;

head = NULL;
while(choice != 0)
{
printf("1. Create List\n");
printf("2. Display list\n");
printf("3. Insert at beginning\n");
printf("4. Insert at any position\n");
printf("0. Exit\n");
printf("--------------------------------------------\n");
printf("Enter your choice : ");

scanf("%d", &choice);

switch(choice)
{
case 1:
printf("Enter the total number of nodes in list: ");
scanf("%d", &n);
createList(n);
break;
case 2:
displayList();
break;
case 3:
printf("Enter data to be inserted at beginning: ");
scanf("%d", &data);
insertAtBeginning(data);
break;
case 4:
printf("Enter node position: ");
scanf("%d", &n);
printf("Enter data you want to insert at %d position: ", n);
scanf("%d", &data);
insertAtN(data, n);
break;
case 0:
break;
default:
printf("Error! Invalid choice. Please choose between 0-4");
}

printf("\n\n\n\n\n");
}

return 0;
}

void createList(int n)
{
int i, data;
struct node *prevNode, *newNode;

if(n >= 1)
{

head = (struct node *)malloc(sizeof(struct node));

printf("Enter data of 1 node: ");


scanf("%d", &data);
head->data = data;
head->next = NULL;

prevNode = head;

for(i=2; i<=n; i++)


{
newNode = (struct node *)malloc(sizeof(struct node));

printf("Enter data of %d node: ", i);


scanf("%d", &data);

newNode->data = data;
newNode->next = NULL;

prevNode->next = newNode;

prevNode = newNode;
}
prevNode->next = head;

printf("\nCIRCULAR LINKED LIST CREATED SUCCESSFULLY\n");


}
}

void displayList()
{
struct node *current;
int n = 1;
if(head == NULL)
{
printf("List is empty.\n");
}
else
{
current = head;
printf("DATA IN THE LIST:\n");

do {
printf("Data %d = %d\n", n, current->data);

current = current->next;
n++;
}while(current != head);
}
}

void insertAtBeginning(int data)


{
struct node *newNode, *current;

if(head == NULL)
{
printf("List is empty.\n");
}
else
{

newNode = (struct node *)malloc(sizeof(struct node));


newNode->data = data;
newNode->next = head;

current = head;
while(current->next != head)
{
current = current->next;
}
current->next = newNode;

head = newNode;

printf("NODE INSERTED SUCCESSFULLY\n");


}
}

void insertAtN(int data, int position)


{
struct node *newNode, *current;
int i;

if(head == NULL)
{
printf("List is empty.\n");
}
else if(position == 1)
{
insertAtBeginning(data);
}
else
{

newNode = (struct node *)malloc(sizeof(struct node));


newNode->data = data;

current = head;
for(i=2; i<=position-1; i++)
{
current = current->next;
}

newNode->next = current->next;
current->next = newNode;

printf("NODE INSERTED SUCCESSFULLY.\n");


}
}
5)Code for deletion from a circular linked list in C language:
#include<stdio.h>
#include<stdlib.h>
struct Node
{
int data;
struct Node *next;
};

int calcSize(struct Node* head);

void deleteFront(struct Node** head){


struct Node* tempNode = *head;

if(*head == NULL){
printf("Linked List Empty, nothing to delete");
return;
}
if(tempNode->next == *head){
*head = NULL;
return;
}

struct Node* curr = *head;

while(curr->next != *head)
curr = curr->next;

curr->next = (*head)->next;

*head = (*head)->next;
free(tempNode);
}

void deleteEnd(struct Node** head){


struct Node* tempNode = *head;
struct Node* previous;

if(*head == NULL){
printf("Linked List Empty, nothing to delete");
return;
}
if(tempNode->next == *head){
*head = NULL;
return;
}

while (tempNode->next != *head)


{
previous = tempNode;
tempNode = tempNode->next;
}
previous->next = *head;
free(tempNode);
}

void deletePos(struct Node** head, int n){

int size = calcSize(*head);

if(n < 1 || size < n) {


printf("Can't delete, %d is not a valid position\n", n);
}

else if(n == 1)
deleteFront(head);

else if(n == size)


deleteEnd(head);

else {
struct Node* tempNode = *head;
struct Node* previous;
while (--n) {
previous = tempNode;
tempNode = tempNode->next;
}
previous->next = tempNode->next;
free(tempNode);
}
}

void insert(struct Node** head, int data)


{
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;

if(*head == NULL){
*head = newNode;
(*head)->next = *head;
return;
}

struct Node* curr = *head;

while(curr->next != *head){
curr = curr->next;
}

curr->next = newNode;
newNode->next = *head;
*head = newNode;
}

int calcSize(struct Node* head){


int size = 0;
struct Node* temp = head;

if(temp == NULL)
return size;

do{
size++;
temp = temp->next;

}while(temp!=head);

return size;
}

void display(struct Node* head)


{
if(head == NULL)
return;

struct Node* temp = head;

do{
printf("%d ", temp->data);
temp = temp->next;
}while(temp!=head);
printf("\n");
}

int main(){

struct Node* head = NULL;

insert(&head,10);
insert(&head,11);
insert(&head,12);
insert(&head,13);
insert(&head,14);
insert(&head,15);
insert(&head,16);

display(head);

deleteFront(&head);
display(head);

deleteEnd(&head);
display(head);

deletePos(&head, 3);
display(head);

return 0;
}
6) Code to reverse a linked list using C language:
#include<stdio.h>
#include<stdlib.h>

struct Node
{
int data;
struct Node* next;
};

static void reverse(struct Node** head_ref)


{
struct Node* prev = NULL;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head_ref = prev;
}

void push(struct Node** head_ref, int new_data)


{

struct Node* new_node =


(struct Node*) malloc(sizeof(struct Node));

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;
}

void printList(struct Node *head)


{
struct Node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}

int main()
{
struct Node* head = NULL;
push(&head, 26);
push(&head, 27);
push(&head, 28);
push(&head, 29);

printf("Given linked list\n");


printList(head);
reverse(&head);
printf("\nReversed Linked list \n");
printList(head);
getchar();
}

7) Code to implement a stack using array in C language:


#include<stdio.h>
int stack[100],choice,n,top,x,i;
void push(void);
void pop(void);
void display(void);
int main()
{
top=-1;
printf("\n Enter the size of STACK[MAX=100]:");
scanf("%d",&n);
printf("\n\t STACK OPERATIONS USING ARRAY");
printf("\n\t--------------------------------");
printf("\n\t 1.PUSH\n\t 2.POP\n\t 3.DISPLAY\n\t 4.EXIT");
do
{
printf("\n Enter the Choice:");
scanf("%d",&choice);
switch(choice)
{
case 1:
{
push();
break;
}
case 2:
{
pop();
break;
}
case 3:
{
display();
break;
}
case 4:
{
printf("\n\t EXIT POINT ");
break;
}
default:
{
printf ("\n\t Please Enter a Valid Choice(1/2/3/4)");
}

}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\tSTACK is over flow");

}
else
{
printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t Stack is under flow");
}
else
{
printf("\n\t The popped elements is %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\n The elements in STACK \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
printf("\n Press Next Choice");
}
else
{
printf("\n The STACK is empty");
}

}
8) Code to implement stacks in linked list in C language:
#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;

int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");

create();

while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);

switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}

void create()
{
top = NULL;
}

void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}

void display()
{
top1 = top;

if (top1 == NULL)
{
printf("Stack is empty");
return;
}

while (top1 != NULL)


{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}

void pop()
{
top1 = top;

if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}

int topelement()
{
return(top->info);
}

void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}

void destroy()
{
top1 = top;

while (top1 != NULL)


{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;

printf("\n All stack elements destroyed");


count = 0;
}
9) use an abstract data type called stack and show how to choose the implementation between
array and linked list during runtime.
10)
11) Code to evaluate inflix expression in Python language:
a=input("Enter a infix expression")
def checkInfix(expression):
if(expression.count('(')==expression.count(')')):
return True
else:
return False

if(checkInfix(a)):
print("The given expression is valid infix expression")
else:
print("The given expression is not a valid infix expression")

12) Code to implement queue using a linked list in C language:


#include <stdio.h>
#include <stdlib.h>

struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;

int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();

int count = 0;

void main()
{
int no, ch, e;

printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Display");
printf("\n 7 - Queue size");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
queuesize();
break;
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}

void create()
{
front = rear = NULL;
}

void queuesize()
{
printf("\n Queue size : %d", count);
}

void enq(int data)


{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;

rear = temp;
}
count++;
}

void display()
{
front1 = front;

if ((front1 == NULL) && (rear == NULL))


{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}

void deq()
{
front1 = front;

if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}

int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}

void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}

13) Code to implement a stack with given two queues in C language:


#include <stdio.h>
#include <stdlib.h>

#define QUEUE_EMPTY_MAGIC 0xdeadbeef


typedef struct _queue_t {
int *arr;
int rear, front, count, max;
} queue_t;
queue_t *queue_allocate(int n);
void queue_insert(queue_t * q, int v);
int queue_remove(queue_t * q);
int queue_count(queue_t * q);
int queue_is_empty(queue_t * q);

void stack_push(queue_t * q, int v) {


queue_insert(q, v);
}

int stack_pop(queue_t * q) {
int i, n = queue_count(q);
int removed_element;

for (i = 0; i < (n - 1); i++) {


removed_element = queue_remove(q);
queue_insert(q, removed_element);

}
removed_element = queue_remove(q);

return removed_element;
}

int stack_is_empty(queue_t * q) {
return queue_is_empty(q);
}

int stack_count(queue_t * q) {
return queue_count(q);
}

int queue_count(queue_t * q) {
return q->count;
}

queue_t *
queue_allocate(int n) {
queue_t *queue;

queue = malloc(sizeof(queue_t));
if (queue == NULL)
return NULL;
queue->max = n;

queue->arr = malloc(sizeof(int) * n);


queue->rear = n - 1;
queue->front = n - 1;

return queue;
}

void queue_insert(queue_t * q, int v) {


if (q->count == q->max)
return;

q->rear = (q->rear + 1) % q->max;


q->arr[q->rear] = v;
q->count++;
}

int queue_remove(queue_t * q) {
int retval;

if (q->count == 0)
return QUEUE_EMPTY_MAGIC;

q->front = (q->front + 1) % q->max;


retval = q->arr[q->front];
q->count--;

return retval;
}

int queue_is_empty(queue_t * q) {
return (q->count == 0);
}

void queue_display(queue_t * q) {
int i = (q->front + 1) % q->max, elements = queue_count(q);

while (elements--) {
printf("[%d], ", q->arr[i]);
i = (i >= q->max) ? 0 : (i + 1);
}
}

#define MAX 128


int main(void) {
queue_t *q;
int x, select;
q = queue_allocate(MAX);

do {
printf("\n[1] Push\n[2] Pop\n[0] Exit");
printf("\nChoice: ");
scanf(" %d", &select);

switch (select) {
case 1:
printf("\nEnter value to Push:");
scanf(" %d", &x);
/* Pushing */
stack_push(q, x);

printf("\n\n__________________________\nCurrent Queue:\n");

queue_display(q);
printf("\n\nPushed Value: %d", x);

printf("\n__________________________\n");
break;

case 2:
/* Popping */
x = stack_pop(q);

printf("\n\n\n\n__________________________\nCurrent Queue:\n");
queue_display(q);
if (x == QUEUE_EMPTY_MAGIC)
printf("\n\nNo values removed");
else
printf("\n\nPopped Value: %d", x);

printf("\n__________________________\n");
break;

case 0:
printf("\nQutting.\n");
return 0;

default:
printf("\nQutting.\n");
return 0;
}
} while (1);

return 0;
}
14) Code to implement a queue using two stacks in C language:
#include <stdio.h>
#include<stdlib.h>
#define N 100

int stack1[N], stack2[N];


int top_stack1 = -1;
int top_stack2 = -1;

int count = 0;

void push_stack1 (int data)


{
if (top_stack1 == N - 1){
printf ("Stack1 is overflow");
return;
}

else{
top_stack1++;
stack1[top_stack1] = data;
}

return;
}

void push_stack2 (int data)


{
if (top_stack2 == N - 1){
printf ("Stack2 is overflow");
return;
}

else
{
top_stack2++;
stack2[top_stack2] = data;
}

return;

int pop_stack1 ()
{
if (top_stack1 == -1){
printf ("Stack1 is underflow\n");
return -1;
}

return stack1[top_stack1--];
}

int pop_stack2 ()
{

if (top_stack2 == -1)
{
printf ("Stack2 is underflow\n");
return -1;
}
return stack2[top_stack2--];

void enqueue (int data)


{
push_stack1 (data);
count++;

void dequeue ()
{
if (top_stack1 == -1 && top_stack2 == -1)
printf ("Queue is empty\n");

else {
for (int i = 0; i < count; i++){

int temp = pop_stack1 ();


push_stack2 (temp);
}

int x = pop_stack2 ();

printf ("Dequeued element is %d\n", x);


count--;

for (int i = 0; i < count; i++){


int temp = pop_stack2 ();
push_stack1 (temp);

}
}
}

void display ()
{
if (top_stack1 == -1)
{
printf ("Queue is empty \n");
return;
}

for (int i = 0; i < top_stack1; i++)


printf ("%d ", stack1[i]);

printf ("\n");

void top ()
{
printf ("Top element of queue is %d ", stack1[0]);
}

int main ()
{
enqueue (3);
enqueue (45);
enqueue (-1);

display();

dequeue ();
enqueue (-1);

display ();

return 0;

15) Applications of stacks:


 Stack is used for evaluating expression with operands and operations.
 Matching tags in HTML and XML
 Undo function in any text editor.
 Infix to Postfix conversion.
 Stacks are used for backtracking and parenthesis matching.
 Stacks are used for conversion of one arithmetic notation to another arithmetic
notation.
 Stacks are useful for function calls, storing the activation records and deleting
them after returning from the function. It is very useful in processing the
function calls.
 Stacks help in reversing any set of data or strings.
16) Applications of queues:
 Multi programming: Multi programming means when multiple programs are
running in the main memory. It is essential to organize these multiple programs
and these multiple programs are organized as queues.
 Network: In a network, a queue is used in devices such as a router or a switch.
another application of a queue is a mail queue which is a directory that stores
data and controls files for mail messages.
 Job Scheduling: The computer has a task to execute a particular number of jobs
that are scheduled to be executed one after another. These jobs are assigned to
the processor one by one which is organized using a queue.
 Shared resources: Queues are used as waiting lists for a single shared resource.

You might also like