0% found this document useful (0 votes)
17 views44 pages

VLR Ec304

The document describes an assignment on comparing the performance of insertion sort, bubble sort, and selection sort algorithms. It involves: 1) Implementing the three sorting algorithms and a function to run them on input arrays. 2) Measuring the execution time of each algorithm for varying input sizes. 3) Plotting a graph of array size versus execution time for each algorithm to compare their performance.

Uploaded by

Mayank Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views44 pages

VLR Ec304

The document describes an assignment on comparing the performance of insertion sort, bubble sort, and selection sort algorithms. It involves: 1) Implementing the three sorting algorithms and a function to run them on input arrays. 2) Measuring the execution time of each algorithm for varying input sizes. 3) Plotting a graph of array size versus execution time for each algorithm to compare their performance.

Uploaded by

Mayank Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 44

1

Dayalbagh Educational Institute (Deemed University)


Agra – 282005

Faculty of Engineering
Academic Semester: July – December 2021

Virtual Laboratory Record

Course No. and Title: EEM 304 – C Lab


Course Teachers: Prof. C. Patvardhan & Dr. V. Prem Prakash

Submitted by:
Name : : Mohammad Shabaz
Roll No. : 2002061
Branch : Civil
2

Contents
Asg. No. Assignment Title Start Date Submit Date Page No.
1. Prime or Composite , Implement Sieve of 09/08/2021 15/08/2021
Eratosthenes, Find Factorial
2. Insertion sort; comparison of time taken by 17/08/2021 22/08/2021
insertion ,bubble and selection sort.
3. Multiplication of two matrix; Sparse matrix 22/08/2021 05/09/2021
addition
4. Tower of Hanoi; Recursive sum of squares 21/09/2021 25/09/2021
5. Array implementation of stack 27/09/2021 2/10/2021
6. Linked List Implementation 19/10/2021 23/10/2021
7. Linked list implementation of stack 10/11/2021 14/11/2021
3

Date: 15/08/2021 Assignment No.:01


Assignment Title: Prime or Composite , Implement Sieve of Eratosthenes, Find Factorial

1. Problem Statement :
1a.
Write a function: int primetest(int NUM) that takes an integer NUM as
argument and returns 0 if NUM is composite or 1 if NUM is PRIME. Inside
main(), read a single integer value as input, test whether the number is prime or
composite by calling the function primetest(NUM) above, and print PRIME or
COMPOSITE accordingly.

1b.
Write a function: void sieve(int N) that takes the value of N as argument and
prints all prime numbers <= N (using the Sieve of Eratosthenes). Inside main(),
read the value of N (an integer) and call sieve(N).

1c.
Write a recursive function int factrec(int N) that takes an integer N as
argument and recursively computes and returns the value of N!

2. Solution Strategy :
(a) For a prime number its factor will only be itself and 1 whereas if more than 2 factors exist
then it will be composite number.

(b) If any particular number is composite then all of its factors will definitely be composite.

(c) A factorial of any number n is the multiplication of number from 1 to n

3. Algorithm/ Pseudo-code:
(a) We will divide the number from 2 and keep dividing till square root of n. We will initialise a count
to zero and if the number divides the given number then we will increase the count. In the end we
will check if the count if it is 1 then it will be PRIME or else it will be COMPOSITE

(b) Create a list of consecutive integers from 2 to n: (2, 3, 4, …, n). Initially, let p equal 2, the first
prime number. S tarting from p 2 , count up in increments of p and mark each of these numbers
greater than or equal to p 2 itself in the list. These numbers will be p(p+1), p(p+2), p(p+3), etc. Find
the first number greater than p in the list that is not marked. If there was no such number, stop.
Otherwise, let p now equal this number (which is the next prime), and repeat.

(c) Int factrec(int N)

{ if (N=1)

return 1;

else
4

return N*factrec(N-1);

4. Source code of solution:

1a.
#include<stdio.h>

#include<math.h>

int primetest(int num)

int c,i;

c=0;

for(i=2;i<=(int)(sqrt(num));i++)

{if(num%i==0)

c++;

if(c==0)

return 1;

else

return 0;

main()

int n,k;

scanf("%d",&n);

if(n!=1&&n!=0)

{k=primetest(n);

if(k==1)

printf("PRIME");

else
5

printf("COMPOSITE");

else

printf("NEITHER PRIME NOR COMPOSITE");

1b.
#include<stdio.h>

void sieve(int n)

int a[500],i,j;

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

a[i]=1;

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

for(j=i+1;j<=n;j++)

if(j%i==0)

a[j]=0;

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

{if(a[i]==1)

printf("%d ",i);

main()

{int n;

scanf("%d",&n);

sieve(n);
6

1c.
#include<stdio.h>

unsigned long long factrec(int n)

unsigned long long fact;

if(n==0)

fact=1;

else

fact=n*factrec(n-1);

return(fact);

main()

int n;

unsigned long long t;

scanf("%d",&n);

t=factrec(n);

printf("%llu",t);

5. Screen-shots of program runs on test cases provided:


7
8

Date: 22/08/2021 Assignment No.:02


Assignment Title: insertion sort; comparison of time taken by insertion ,bubble and selection sort.

1. Problem Statement :
2a.
Write a function: void insertionsort(int a[], int N, int choice)that
reads N ints and sorts them using insertion sort in ascending or descending
order, depending on what the user specifies (an additional integer variable
that is 0 for ascending and 1 for descending order). The function should
print the sorted list, with numbers separated by a single space.
Your program should read N first, then choice, then N integer elements (in
that order) and then call the insertionsort() function above.

2b.
Similarly write two more functions, one each for selectionsort and bubblesort, in
another source file (...02b.c):

void selectionsort(int a[], int N, int choice)


void bubblesort(int a[], int N, int choice)

Add the insertionsort() function from 02a to this file, and run all three functions on
different input sizes. Plot the array size (x axis) versus execution time (y) for all
three algorithms, going up to the largest possible array size supported by your
programming environment. You may use MS Excel or any other software for
generating the graph. If you don;t have access to any such software, draw the
graph to scale on an A4 sheet. Submit the graph as a JPF/PNG image. Ensure that
image size is well within the permitted submission limit (500 KB)
9

2. Solution Strategy :
2 (a) Like matrix multiplication we will multiply the matrix cells with each other and print the
output.
2. (b) To add sparse matrix we will follow simple matrix addition method.

3. Algorithm/ Pseudo-code:

2a.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 2 − Pick next element
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the value to be
sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

2b.
Implementing selectionsort algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted

Implementing Bubble Sort Algorithm


1.Starting with the first element(index = 0), compare the current element with the next
element of the array.
2.If the current element is greater than the next element of the array, swap them.
3.If the current element is less than the next element, move to the next element. Repeat
Step 1.

4. Source code of solution:

2a.
#include<stdio.h>

void insertionsort(int a[100],int N,int choice)


{int i,j,t;
if(choice==0)
{ for(i=0;i<N;i++)
10

{
t=a[i];
j=i-1;
while(j>=0&&a[j]>t)
{
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}

}
if(choice==1)
{
for(i=0;i<N;i++)
{
t=a[i];
j=i-1;
while(j>=0&&a[j]<t)
{
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}
}
for(i=0;i<N;i++)
{
printf("%d ",a[i]);
}
}
main()
{
int a[100],i,j,t,n,choice;
scanf("%d",&n);
scanf("%d",&choice);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
insertionsort(a,n,choice);

2b.
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
void selectionsort(long int a[],long int N,int choice)
{long int i,j;
long int pos,t;
if(choice==0)
{ for(i=0;i<N;i++)
11

pos=i;
for(j=i+1;j<N;j++)
{
if(a[j]<a[pos])
{
pos=j;

}
}
if(pos!=i)
{t=a[i];
a[i]=a[pos];
a[pos]=t;

}
}
}
if(choice==1)
{
for(i=0;i<N;i++)
{

pos=i;
for(j=i+1;j<N;j++)
{
if(a[j]>a[pos])
{
pos=j;

}
}
if(pos!=i)
{t=a[i];
a[i]=a[pos];
a[pos]=t;

}
}

}
}
void insertionsort(long int a[],long int N,int choice)
{long int i,j,t;
if(choice==0)
{ for(i=0;i<N;i++)
{
t=a[i];
j=i-1;
while(j>=0&&a[j]>t)
{
a[j+1]=a[j];
j--;
12

}
a[j+1]=t;
}

}
if(choice==1)
{
for(i=0;i<N;i++)
{
t=a[i];
j=i-1;
while(j>=0&&a[j]<t)
{
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}
}

}
void bubblesort(long int a[], long int n,int choice)
{long int i,j;

if(choice==0)
{
for (long int i = 0; i < n - 1; i++) {
for (long int j = 0; j < n - 1 - i; j++) {
if (a[j] > a[j + 1]) {
long t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}
if(choice==1)
{
for (long int i = 0; i < n - 1; i++) {
for (long int j = 0; j < n - 1 - i; j++) {
if (a[j] < a[j + 1]) {
int t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
}
}
}

int main()
{
long int n;
13

int choice;

double t1,t2,t3;

printf("Enter no. of elements: ");


scanf("%li",&n);
printf("\nEnter choice ");
scanf("%d",&choice);

long int a[100000], b[100000], c[100000];

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


long int no = rand()%n + 1;
a[i] = no;
b[i] = no;
c[i] = no;
}

clock_t t;

t = clock();
bubblesort(a, n,choice);
t = clock()-t;

t1 = ((double)(t))/CLOCKS_PER_SEC;

t = clock();
insertionsort(b, n,choice);
t = clock()-t;

t2 = ((double)(t))/CLOCKS_PER_SEC;

t = clock();
selectionsort(c, n,choice);
t= clock()-t;

t3 = ((double)(t))/CLOCKS_PER_SEC;

printf("No. of elements= %li\nTime taken by bubble sort= %lf\nTime


taken by insertion sort= %lf\nTime taken by selection sort= %lf\
n",n,t1,t2,t3);

return 0;
}
14

5. Screen-shots of program runs on test cases provided:

Date: 05/09/2021 Assignment No.:03


Assignment Title: multiplication of two matrix; Sparse matrix addition

1. Problem Statement :

3a.
Matrix Multiplication. Write the following two functions:
void matmult(int A[][MAX], int B[][MAX], int C[][MAX], int P, int
Q, int R)
(A function that multiplies two matrices, APxQ and BQxR and stores the
result in matrix CPxR)
void display(int A[][MAX], int rows, int cols)
(A function that prints the contents of matrix A rows x cols row by row, with a
single space between elements within a row)
Your program should be able to support up to 500x500 (MAX=500) element
arrays (Assume this to be the maximum size of array that we will be
testing the program on). The program will read the values of P, Q and R,
followed by PQ + QR elements from the keyboard. All these would be
stored in the input files provided. These elements would be read into
arrays A and B respectively. The program should check if the dimensions
of the two matrices are compatible for the operation. Appropriate error
message should be printed in case either of these conditions fails. The
program should call the matmult() function to perform the multiplication
operation C=AxB, and then display the matrix C using
the display() function.
15

3b.
Sparse Matrix Addition. Write a program that reads two sparse matrices,
adds them and display the resulting sum matrix. Input will be provided in the
test files in the following order:
nrowsA ncolsA nelemsA nrowsB ncolsB nelemsB row1A col1A val1A row2A col2A
… row1B col1B val1B row2B col2B … (single space separated). Assume that no
source matrix (A or B) may contain more than 100 entries.

2. Solution Strategy :
3a.

Firstly, we will initialize the variables accordingly. After that we will insert the matrix elements by
row wise and multiply them using loops. Then, we will store the final multiplication and get the
desired output.

3b.

Firstly, we will initialize the variables accordingly. After that we will insert the sparse matrix elements
by row wise and add them using loops. Then, we will store the final addition and get the desired
output.

3. Algorithm/ Pseudo-code:

3a.
1. Start

2. Declare variables and initialize necessary variables

3. Enter the element of matrices by row wise using loops

4. Check the number of rows and column of first and second matrices

5. If number of rows of first matrix is equal to the number of columns of second matrix, go to step 6.
Otherwise, print matrix multiplication is not possible and go to step 3.

6. Multiply the matrices using nested loops.

7. Print the product in matrix form as console output.

8. Stop

3b.
16

To Add the matrices, we simply traverse through both matrices element by element and insert the
smaller element (one with smaller row and col value) into the resultant matrix. If we come across an
element with the same row and column value, we simply add their values and insert the added data
into the resultant matrix.

4. Source code of solution:

3a.
#include<stdio.h>

#include<stdlib.h>

#define MAX 500

void matmult(int A[][MAX],int B[][MAX],int C[][MAX],int P, int Q, int R)

{int k=0,i,j,l;

for(i=0;i<P;i++)

{for(l=0;l<R;l++)

for(j=0;j<Q;j++)

k=

A[i][j]*B[j][l]+k;

C[i][l]=k;
17

k=0;

display(C,P,R);

void display(int C[][MAX],int P,int R)

{ int i,j;

for(i=0;i<P;i++)

{for(j=0;j<R;j++)

printf("%d ",C[i][j]);

printf("\n");

int main()

static int a[MAX][MAX],b[MAX][MAX],i,j,l,P,Q,R;

static int C[MAX][MAX];

scanf("%d%d%d",&P,&Q,&R);

for(i=0;i<P;i++)

{
18

for(j=0;j<Q;j++)

scanf("%d",&a[i][j]);

for(i=0;i<Q;i++)

for(j=0;j<R;j++)

scanf("%d",&b[i][j]);

matmult(a,b,C,P,Q,R);

return 0;

3b.
#include<stdio.h>

#include<stdlib.h>

#define MAX 400

int main()

int a[MAX][3],b[MAX][3],c[MAX][3],i,j,n,m,R,F,r,f;

scanf("%d%d%d",&R,&F,&n);

scanf("%d%d%d",&r,&f,&m);

if(R!=r||F!=f)

printf("Wrong matrix size");


19

exit(0);

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

for(j=0;j<3;j++)

scanf("%d",&a[i][j]);

for(i=0;i<m;i++)

for(j=0;j<3;j++)

scanf("%d",&b[i][j]);

int p=0,q=0;

i=0;

while(p!=n || q!=m)

if(a[p][0]==b[q][0])

if(a[p][1]==b[q][1])

{ c[i][0]=a[p][0];

c[i][1]=a[p][1];

c[i][2]=a[p][2]+b[q][2];

i++;

p++;

q++;

}
20

else

if(a[p][1]<b[q][1])

{ c[i][0]=a[p][0];

c[i][1]=a[p][1];

c[i][2]=a[p][2];

i++;

p++;

else

{c[i][0]=b[q][0];

c[i][1]=b[q][1];

c[i][2]=b[q][2];

i++;

q++;

else

if(a[p][0]<b[q][0])

{ c[i][0]=a[p][0];

c[i][1]=a[p][1];

c[i][2]=a[p][2];
21

i++;

p++;

else

{c[i][0]=b[q][0];

c[i][1]=b[q][1];

c[i][2]=b[q][2];

i++;

q++;

int s;

int k=i;

if(p!=n)

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

for(j=0;j<3;j++)

{c[k][j]=a[i][j];

k++;

if(q!=m)
22

for(i=q;i<m;i++)

for(j=0;j<3;j++)

{c[k][j]=b[i][j];

k++;

printf("%d %d %d\n",r,f,k);

for(s=0;s<k;s++)

for(j=0;j<3;j++)

printf("%d ",c[s][j]);

printf("\n");

return 0;

5. Screen-shots of program runs on test cases provided:


23

Date: 25/09/2021 Assignment No.:04


Assignment Title:tower of Hanoi; Recursive sum of squares
24

1.Problem Statement :

4a.
Towers of Hanoi using recursion. Given three poles A, B and C, and a stack on n
disks of increasing diameters, numbered 1, 2, 3 … respectively mounted on pole
A, move this stack to pole C, obeying the following rules:
1) Only one disk is to be moved at a time. More than one disk cannot be picked up
simultaneously.
2) A move consists of taking the uppermost disk from one of the stacks and
placing it on top of another stack. So a disk can only be moved if it is the
uppermost disk on a stack.
3) No disk may be placed on top of a smaller disk.
You will write a recursive function for this purpose, to be called from main(),
which will read the value of n redirected from input test file (plus additional
arguments for the source/dest/aux poles) and print a string of moves representing
the correct sequence of <disk#,sourcepole,destpole> moves that represent the
solution.

4b.
Recursive Sum-of-Squares Write a recursive function findSum() that takes an
array A of integers and two indices (lo and hi, lo <=hi) as arguments and returns
(A[lo]2+ A[lo+1]2… A[hi]2).

int findSum(int A[], int lo, int hi)

Your program will receive as input the value of N (the number of array elements)
followed by N array elements separated by single spaces, followed by hi and lo
index values, separated by single spaces as before. The output of your program
should be a single integer that represents the sum of squares of the array
elements between indices lo and hi.

2. Solution Strategy :
(a) Only one disk can be moved at a time. Each move consists of taking the upper disk from one of
the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost
disk on a stack. No disk may be placed on top of a smaller disk.

(b) We can find the sum of square using simple mathematical and logical expressions.

3. Algorithm/ Pseudo-code:
3(a) Step 1: Shift first disk from 'A' to 'B'.

Step 2: Shift second disk from 'A' to 'C'.


25

Step 3: Shift first disk from 'B' to 'C'. Shift 'n-1' disks from 'A' to 'B'. Shift last disk from 'A' to 'C'. Shift
'n-1' disks from 'B' to 'C'.

3(b) We can recursively call the function from lo to hi and at each step we will add to a variable SUM
and then at the end we will print the sum.

4. Source code of solution:

4a.
#include<stdio.h>

void hanoi(int n,char A,char B,char C)

{if(n==1)

printf("%d%c%c",n,A,C);

else

{hanoi(n-1,A,C,B);

printf("%d%c%c",n,A,C);

hanoi(n-1,B,A,C);

main()

{int x;

scanf("%d",&x);

hanoi(x,'A','B','C');

4b.
#include<stdio.h>

int findSum(int A[],int lo, int hi)

{int sum;

if(lo<=hi)
26

sum=A[lo]*A[lo]+findSum(A,lo+1,hi);

return sum;}

main()

int i,lo,hi,a[100],num,sum;

scanf("%d",&num);

for(i=0;i<num;i++)

scanf("%d",&a[i]);

scanf("%d%d",&lo,&hi);

if(hi<num && lo<hi)

{sum=findSum(a,lo,hi);

printf("%d",sum);

5. Screen-shots of program runs on test cases provided:


27

Date:20 sept 2020 Assignment No.:05


Assignment Title:array implementation of stack

1.Problem Statement :
Write push(), pop(), isFull() and isEmpty() functions for an integer stack. Create a menu-driven
program that repeatedly takes one of the following four options as input: 1, 2 ,3 or 4 for PUSH, POP,
DISPLAY and EXIT respectively, and performs the appropriate sequence of actions. As discussed in
the class, you must ensure that there are no extraneous printf statements in your code. Note that
DISPLAY prints stack elements in order from A[0] up to A[TOP]. Test input will comprise of a series of
PUSH/POP followed by DISPLAY and EXIT. Any attempts to PUSH onto a full stack or POP from an
empty stack should be simply ignored by your program, i.e., it should not even print any error
message. Assume that the maximum stack size is 10 elements.

2. Solution Strategy :
We have to initialise a stack with function pop, push and isEmpty. It will perform the operation such
as POP, PUSH, DISPLAY, EXIT. To perform such operations we will implement a menu driven format
from which the users will be able to choose which operation to perform.

3. Algorithm/ Pseudo-code:
For Push function

if (stack is full)

return null

else if

top ++

stack[top] = data

For Pop function

if (stack is empty)

return null
28

else if

data= stack[top]

top --

return data

For Isfull function

if (top equals to MAXSIZE)

return true

else

return false

For Isempty function

if (top less than 1)

return true

else

return false

4. Source code of solution:


#include<stdio.h>

int a[100];

int top=-1;

void display()

{int i=0;

while(i<=top)

printf("%d ",a[i++]);

}
29

void push()

{ int n;

scanf("%d",&n);

top=top+1;

a[top]=n;

void pop()

top=top-1;

int isEmpty()

if(top==-1)

return 1;

else

return 0;

int isFull()

if(top==99)

return 1;

else

return 0;
30

main()

{int n,ch=0;

while(ch!=4)

scanf("%d",&ch);

switch(ch)

case 1: if(!isFull())

push();

break;

case 2: if(!isEmpty())

pop();

break;

case 3: display();

break;

case 4:break;

5. Screen-shots of program runs on test cases provided:


31

Date: 2/10/2021 Assignment No.:06


Assignment Title: Linked List Implementation

1.Problem Statement :
Create a singly linked list of integer values. Implement functions for inserting at the head of the list,
inserting an element before or after another specified element in the list, deleting a given element
and simple list traversal. Use the C template (Asg06_template.c) given to you for this purpose. DO
NOT MAKE ANY CHANGES to the main() program and the structure definitions given in the template.
Your job in this assignment is only to implement the functions declared and used in this program.
The behaviour of the program is also clearly explained in the associated video. Please go through it
and carefully implement your solution in the same template file, rename it properly and submit.

2. Solution Strategy :
A linked list consists of nodes where each node contains a data field and a reference(link) to the next
node in the list. methods to insert a new node in linked list are discussed. A node can be added in
three ways

a) At the front of the linked list

b) After a given node.

c) At the end of the linked list.

To delete a node from the linked list, we need to do the following steps.

a) Find the previous node of the node to be deleted.


32

b) Change the next of the previous node.

c) Free memory for the node to be deleted.

To print we will simply traverse the list node by node starting from head and print the data of each
node.

3. Algorithm/ Pseudo-code:
For Insertion at Head

X=new node

if (head=NULL) then

head=X

next(X)=NULL

else

next(X)=head

head=X

For Insertion after a node

ptr=list

while (ptr not NULL)

if (data(ptr)=’val’)

X=new node

next(X)=next(ptr)

next(ptr)=X
33

break

ptr=next(ptr)

For Insertion before a node

ptr=list

if(data(ptr)=’val’)

X=new node

next(X)=list

list=X

stop

while(ptr not NULL )

tpt=ptr

ptr=next(ptr)

if(data(ptr)=’val’)

X=new node

next(X)=ptr

next(tpt)=X

exit

}
34

For Deletion

if (data(list)=’val’)

ptr=list

list=next(list)

delete ptr

stop

tpt=list

ptr=list

while(ptr not NULL)

if(data(ptr)=’val’)

next(tpt)=next(ptr)

delete ptr

exit

tpt=ptr

ptr=next(ptr)

4. Source code of solution:


#include <stdio.h>

#include <malloc.h>

typedef struct node_tag

{
35

int val;

struct node_tag *next;

} node;

node *head;

int

main ()

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

int i, n, before, after, itemBefore, itemAfter, itemDelete;

void insertAtHead (int n);

void insertBefore (int itembefore, int before);

void insertAfter (int itemafter, int after);

void traverse (void);

void deleteItem (int itemdelete);

scanf ("%d", &n);

scanf ("%d", &itemBefore);

scanf ("%d", &before);

scanf ("%d", &itemAfter);

scanf ("%d", &after);

scanf ("%d", &itemDelete);

insertAtHead (0);

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

insertAfter (i, i - 2);

insertAfter (itemAfter, after);

insertBefore (itemBefore, before);

deleteItem (itemDelete);

traverse ();

return 0;

/* your functions go here */

/*void insertAtHead (int x)

head->val = x;

head->next = NULL;

} */

void insertAtHead(int x)

{ node *temp=(node*)malloc(sizeof(node));

temp->val=x;

temp->next=NULL;

head=temp;

void insertBefore (int itembefore, int before)


37

int i = 0, j = 0,k=0;

node *p;

node *q;

node *r;

q = (node *) malloc (sizeof (node));

p = head;

r = head;

while (p!= NULL)

k++;

if (p->val == before && before != 0)

while (i < k-2)

i++;

r= r->next;

q->val = itembefore;

q->next = p;

r->next = q;

else if (before== 0 && k== 1)

q->val = itembefore;
38

q->next = p;

head = q;

p= p->next;

insertAfter (int itemafter, int after)

node *p;

node *q;

node *r;

q = (node *) malloc (sizeof (node));

p = head;

while (p != NULL)

if (p->val == after)

q->val = itemafter;

r = p->next;

if (r != NULL)

q->next = r;

else

q->next = NULL;

p->next = q;

p = p->next;
39

void deleteItem(int item)

node *p ,*q;

p = head;

while(p!=NULL)

if(p->val == item)

break;

q = p;

p = p->next;

if(p==NULL)

return;

if(p==head)

head = head->next;

else

q->next = p->next;

free(p);

/* Please use the traverse function provided below so that there is no confusion in output */

void traverse (void)


40

node *n = head;

while (n)

printf ("->%d", n->val);

n = n->next;

5. Screen-shots of program runs on test cases provided:


41

Date: 14/11/2021 Assignment No.:07


Assignment Title: Linked list implementation of stack

1.Problem Statement :
Create a linked stack of city names. For this purpose, the template provides you with a structure
called node, which has two elements: a char pointer and a next pointer. Implement functions push()
and pop() for pushing and popping respectively, from the list. The push() function will take two
arguments, the address of the head of the list, and the city name to be pushed. The pop() function
will remove an free the top element of the list, and return the number of characters of the city name
stored in that element. Use the C template (Asg07_template.c) given to you for this purpose. DO
NOT MAKE ANY CHANGES to the main() program and the structure definitions given in the template.
Your job in this assignment is only to implement the functions push() and pop() as required in order
to produce the desired output in this program. The behaviour of the program is also clearly
explained in the associated video. Please go through it and carefully implement your solution in the
same template file, rename it properly and submit

2. Solution Strategy :
We will use stack implemented as linked list and declare pointer to variable. We will allocate some
memory to those nodes and data ( city name) and address to the next node. Then we will implement
the function to carry out the operation such as push and pop. Both the functions are rather not
typical but elementary.

3. Algorithm/ Pseudo-code:

1. Create a node first and allocate memory to it.


2. If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to
the address part of the node.
42

3. If there are some nodes in the list already, then we have to add the new
element in the beginning of the list (to not violate the property of the stack).
For this purpose, assign the address of the starting element to the address
field of the new node and make the new node, the starting node of the list.
This all is the part of the push function.
4. Now we’ll make pop function which will delete the nodes from the beginning
and make the next following node as the head node this all will be performed
till the list becomes empty.This function will also return the length of the city
of the deleted nde.

4. Source code of solution:


#include <stdio.h>

#include <string.h>

#include <malloc.h>

#define SIZE 20

typedef struct node_tag {

char * city;

struct node_tag * next;

} node;

int main () {

node * head=NULL;

int i,n;

char item[SIZE];
43

void push(node **, char []);

int pop (node **);

scanf("%d",&n);

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

scanf("%s",item);

push(&head, item);

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

printf("%d",pop(&head));

return 0;

void push(node ** head, char item[]) {

int len;

len=strlen(item);

node *ptr=(node *)malloc(sizeof(node));

ptr->city=(char *)malloc(len+1);

strcpy(ptr->city,item);

ptr->next=NULL;

if((*head)!=NULL)

ptr->next=(*head);

(*head)=ptr;
44

int pop(node ** head) {

node *ptr;

int len;

if((*head)==NULL)

return;

ptr=(*head);

(*head)=ptr->next;

len=strlen(ptr->city);

free(ptr);

return len;

5. Screen-shots of program runs on test cases provided:

You might also like