You are on page 1of 70

Velammal College of Engineering and Technology, Madurai-09.

Department of Computer Science and Engineering

Regulations 2013

B.E CSE - I YEAR - II SEMESTER

CS6202 – Programming and Data Structures Laboratory - I


Manual

ANNA UNIVERSITY, CHENNAI-600025


Table of Contents

Sl.No. Description

1. Objective and outcome of the course

2. Syllabus of the course

3. List of experiments

4. Requirements

5. Instructions for Assessment

6. Lab Manual
Objective and Outcome of the Course

OBJECTIVES:
The student should be made to:
● Be familiar with C programming
● Be exposed to implementing abstract data types
● Learn to use files
● Learn to implement sorting and searching algorithms

Upon Completion of this course, the student is able to

● Design and implement C programs for implementing stacks, queues, linked lists.
● Apply good programming design methods for program development.
● Apply the different data structures for implementing solutions to practical problems.
● Develop searching and sorting programs.
● Understand the basic data structures
Syllabus

1. C Programs using Conditional and Control Statements


2. C Programs using Arrays, Strings and Pointers and Functions
3. Representation of records using Structures in C – Creation of Linked List – Manipulation
of records in a Linked List
4. File Handling in C – Sequential access – Random Access
5. Operations on a Stack and Queue – infix to postfix – simple expression evaluation using
stacks -Linked Stack Implementation – Linked Queue Implementation
6. Implementation of Sorting algorithms
7. Implementation of Linear search and Binary Search.

TOTAL: 45 PERIODS
List of Experiments

C Programming Decision Making and Loops

1. C Program to Check Whether a Number is Even or Odd


2. C Program to Check Whether a Character is Vowel or consonant
3. C Program to Find the Largest Number Among Three Numbers Entered by User
4. C program to Find all Roots of a Quadratic equation
5. C Program to Check Whether the Entered Year is Leap Year or not
6. C Program to Check Whether a Number is Positive or Negative or Zero.
7. C Program to Checker Whether a Character is an Alphabet or not
8. C Program to Find Sum of Natural Numbers
9. C Program to Find Factorial of a Number
10. C program to Generate Multiplication Table
11. C Program to Display Fibonacci Series
12. C Program to Find HCF of two Numbers
13. C Program to Find LCM of two numbers entered by user
14. C Program to Count Number of Digits of an Integer
15. C Program to Reverse a Number
16. C program to Calculate the Power of a Number
17. C Program to Check Whether a Number is Palindrome or Not
18. C Program to Check Whether a Number is Prime or Not
19. C Program to Display Prime Numbers Between Two Intervals
20. C program to Check Armstrong Number
21. C Program to Display Armstrong Number Between Two Intervals
22. C program to Display Factors of a Number
23. C program to Print Pyramids and Triangles in C programming using Loops
24. C program to Make a Simple Calculator to Add, Subtract,Multiply or Divide Using switch...case
C Programming Function

1. C Program to Display Prime Numbers Between Intervals by Making Function


2. C Program to Check Prime and Armstrong Number by Making Function
3. C program to Check Whether a Number can be Express as Sum of Two Prime Numbers
4. C program to Find Sum of Natural Numbers using Recursion.
5. C program to Calculate Factorial of a Number Using Recursion
6. C Program to Find H.C.F Using Recursion
7. C program to Reverse a Sentence Using Recursion
8. C program to Calculate the Power of a Number Using Recursion
9. C Program to Convert Binary Number to Decimal and Decimal to Binary
10. C Program to Convert Octal Number to Decimal and Decimal to Octal
11. C Program to Convert Binary Number to Octal and Octal to Binary

C Programming Array and Pointer

1. C Programming Examples And Source Code


2. C Program to Calculate Average Using Arrays
3. C Program to Find Largest Element of an Array
4. C Program to Calculate Standard Deviation
5. C Program to Add Two Matrix Using Multi-dimensional Arryas
6. C Program to Multiply to Matrix Using Multi-dimensional Arrays
7. C Program to Find Transpose of a Matrix
8. C Program to Multiply two Matrices by Passing Matrix to Function
9. C Program to Sort Elements of an Array
10. C Program to Access Elements of an Array Using Pointer
11. C Program Swap Numbers in Cyclic Order Using Call by Reference
12. C Program to Find Largest Number Using Dynamic Memory Allocation
String in C Programming

1. C Programming Examples And Source Code


2. C Program to Find the Frequency of Characters in a String
3. C Program to Find the Number of Vowels, Consonants, Digits and White space in a String
4. C Program to Reverse a String by Passing it to Function
5. C Program to Find the Length of a String
6. C program to Concatenate Two Strings
7. C Program to Copy a String
8. C Program to Remove all Characters in a String except alphabet
9. C Program to Sort Elements in Lexicographical Order (Dictionary Order)
10. C Program to Change Decimal to Hexadecimal Number and Vice Versa
11. C Program to Convert Hexadecimal to Octal and Vice Versa
12. C Program to Convert Binary Number to Hexadecimal Vice Versa
C Programming Structure

1. C Program to Store Information(name, roll and marks) of a Student Using Structure


2. C Program to Add Two Distances (in inch-feet) System Using Structures
3. C Program to Add Two Complex Numbers by Passing Structure to a Function
4. C Program to Calculate Difference Between Two Time Period
5. C Program to Store Information of 10 Students Using Structure
6. C Program to Store Information Using Structures for n Elements Dynamically
C Programming File

1. C Program to Create a File & Store Information


2. C Program to Illustrate Reading of Data from a File
3. C Program to Delete a specific Line from a Text File
4. C Program to Replace a specified Line in a Text File
5. C Program to Find the Number of Lines in a Text File
6. C Program to Append the Content of File at the end of Another
7. C Program that Merges Lines Alternatively from 2 Files & Print Result
8. C Program to List Files in Directory
9. C Program to Find Sum of Numbers given in Command Line Arguments Recursively
10. C Program to Display the Function Names defined in C Source File
11. C Program to Find the Size of File using File Handling Function
12. C Program to Capitalize First Letter of every Word in a File
13. C Program to Print Environment Variables
14. C Program to Copy File into Another File
15. C Program to Create Employee Record and Update it
16. C Program to Compare two Binary Files, Printing the First Byte Position where they Differ
17. C Program to Convert the Content of File to Upper Case
18. C Program to Replace First Letter of every Word with Capital Letter
19. C Program to Count No of Lines, Blank Lines, Comments in a given Program
20. C Program to Reverse the Contents of a File and Print it
21. C Program to Convert the Content of File to Lower Case
22. C Program to Update Details of Employee using Files
23. C Program to Create Employee File Name Record that is taken from the Command-Line
Argument
24. C Program to Join Lines of Two given Files and Store them in a New file
25. C Program to Collect Statistics of a Source File like Total Lines, Total no. of Blank Lines, Total
no. of Lines ending with Semicolon
C Programming Linked List

1. C Program to Create a Linked List & Display the Elements in the List
2. C Program to Illustrate the Operations of Singly Linked List
3. C Program to Search for an Element in the Linked List using Recursion
4. C Program to Display the Nodes of a Linked List in Reverse using Recursion
5. C Program Count the Number of Occurrences of an Element in the Linked List using Recursion
6. C Program to Display all the Nodes in a Linked List using Recursion
7. C Program find the Length of the Linked List using Recursion
8. C Program to Print the Alternate Nodes in a Linked List using Recursion
9. C Program to Print the Alternate Nodes in a Linked List without using Recursion
10. C Program find the Length of the Linked List without using Recursion
11. C Program Count the Number of Occurrences of an Element in the Linked List without using
Recursion
12. C Program to Display all the Nodes in a Linked List without using Recursion
13. C Program to Display the Nodes of a Linked List in Reverse without using Recursion
14. C Program to Search for an Element in the Linked List without using Recursion
15. C Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display
Operations
16. C Program to Add Corresponding Positioned Elements of 2 Linked Lists
17. C Program to Check whether 2 Lists are Same
18. C Program to Check whether a Singly Linked List is a Palindrome
19. C Program to Convert a given Singly Linked List to a Circular List
20. C Program to Find Number of Occurences of All Elements in a Linked List
21. C Program to Find the first Common Element between the 2 given Linked Lists
22. C Program to Find the Largest Element in a Doubly Linked List
23. C Program to Print Middle most Node of a Linked List
24. C Program to Read a Linked List in Reverse
25. C Program to Remove Duplicates from a Linked List
26. C Program to Reverse a Linked List
27. C Program to Reverse only First N Elements of a Linked List
28. C Program to Implement Circular Doubly Linked List
29. C Program to Demonstrate Circular Single Linked List
30. C Program to Implement Singly Linked List using Dynamic Memory Allocation
31. C Program to Find Intersection & Union of 2 Linked Lists
32. C Program to Implement Doubly Linked List using Singly Linked List
33. C Program to Interchange the two Adjacent Nodes given a circular Linked List
34. C Program to Interchange two Elements of the List without touching the Key Field
35. C Program to Modify the Linked List such that All Even Numbers appear before all the Odd
Numbers in the Modified Linked List
36. C Program to Print Nth Node from the last of a Linked List
37. C Program to Read a Linked List in Reverse
C Programming Stacks & Queues

1. C Program to Implement a Stack


2. C Program to Reverse a Stack using Recursion
3. C Program to Reverse a Stack without using Recursion
4. C Program to Implement a Queue using an Array
5. C Program to Implement two Stacks using a Single Array & Check for Overflow & Underflow
6. C Program to Implement a Stack using Linked List
7. C Program to Implement Queue Data Structure using Linked List
8. C Program to Implement Priority Queue to Add and Delete Elements
9. C Program to Check String is Palindrome using Stack
10. C Program to Check if Expression is correctly Parenthesized
11. C Program to Implement various Queue Functions using Dynamic Memory Allocation
12. C Program to Implement Stack Operations using Dynamic Memory Allocation
13. C Program to Implement Queues using Stacks
14. C Program to Illustrate Stack Operations using MACROS
15. C Program to Implement Queue using Stack
16. C Program to Identify whether the String is Palindrome or not using Stack
17. C Program to Implement Queue Functions Using Arrays and Macros
C Programming Sorting and Searching

1. C Program to Sort N Numbers in Ascending Order using Bubble Sort


2. C Program to Implement Selection Sort Recursively
3. C Program to Input Few Numbers & Perform Merge Sort on them using Recursion
4. C Program to Perform Quick Sort on a set of Entries from a File using Recursion
5. C Program to Implement Linear Search
6. C Program to Implement Selection Sort Method using Functions
7. C Program to Implement Insertion Sort
8. C Program to Perform Shell Sort without using Recursion
Requirements

Standalone desktops with C compiler 30 Nos.


(or)
Server with C compiler supporting 30 terminals or more.
Instructions for Assessment

● The manual contains the programs for all the model exercises that has been executed on DEV
C++ IDE

● The programs are given here for your quick reference and understanding purposes only. This
is not the actual exercises to be done in the laboratory classes.

● The actual exercises will be given to you in the laboratory classes based on the similar
concepts explained in the model exercises.

● All the laboratory exercises should be implemented in DEV C++ IDE

● All the students are instructed to maintain a hard copy of the manual, separate notebook and
file folder for this course.

● When you come to lab, you have to write the pseudo code for your exercises on spot and then
implement the same on above mentioned IDE. The pseudo code must be prepared on the note
book and all the observations of your implementation must be recorded in the note book, once
you finished your exercises. At the end of the laboratory classes, the note book must be
signed by the faculty in charge and assessment will be done.

● When you are coming for the laboratory classes, the completed record sheets for the previous
class exercises must be produced for signature of faculty in charge except for first class of the
course.

● All the exercises need to be completed in the respective classes itself. The deadline will not be
extended at any circumstances. All the assessment will be done in the same class itself.

● You are encouraged to do all the necessary preparation before you come to the lab. Treat
every lab class as lab examination.

● Every exercise will be assessed for maximum of 100 marks.


1. C Program to Check Whether a Number is Even or Odd

Numbers perfectly divisible by 2 are known even numbers and numbers which are not divisible by
2 are called odd numbers.

This program takes an integer from user and checks whether that number is even or odd and
displays the result.

Step 1: user is asked to enter an integer which is stored in variable num.

Step2: The remainder is found when that number is divided by 2 and checked whether remainder
is 0 or not.

2[a].If remainder is 0 then, that number is even otherwise that number is odd.

Step3: This task is performed using if...else statement in C programming and the result is
displayed accordingly.

#include <stdio.h>

int main(){

int num;

printf("Enter an integer you want to check: ");

scanf("%d",&num);

if((num%2)==0) /* Checking whether remainder is 0 or not. */

printf("%d is even.",num);

else

printf("%d is odd.",num);
return 0;

Output 1

Enter an integer you want to check: 25

25 is odd.

Output 2

Enter an integer you want to check: 12

12 is even.

2. C Program to Check Vowel or Consonant


Alphabets a, e, i, o and u are known as vowels and all alphabets except these characters are known
as consonants.

This program asks user to enter a character and checks whether that character is a vowel or not.
This task can be performed in C programming using if...else statement.

Step1: user is asked to enter a character which is stored in variable c.

Step2:Then, this character is checked, whether it is any one of these ten characters a, A, e, E, i, I,
o, O, u and U using logical OR operator ||.

Step3: If that character is any one of these ten characters, that alphabet is a vowel if not that
alphabet is a consonant.

#include <stdio.h>

int main(){

char c;

printf("Enter an alphabet: ");

scanf("%c",&c);

if(c=='a'||c=='A'||c=='e'||c=='E'||c=='i'||c=='I'||c=='o'||c=='O'||c=='u'||c=='U')

printf("%c is a vowel.",c);

else

printf("%c is a consonant.",c);

return 0;

}
Output 1

Enter an alphabet: i

i is a vowel.

Output 2

Enter an alphabet: G

G is a consonant

3. C Program to Find the Largest Number Among Three Numbers


In this program, user is asked to enter three numbers and this program will find the largest number
among three numbers entered by user.

Source Code 1

#include <stdio.h>

int main(){

float a, b, c;

printf("Enter three numbers: ");

scanf("%f %f %f", &a, &b, &c);

if(a>=b && a>=c)

printf("Largest number = %.2f", a);

if(b>=a && b>=c)

printf("Largest number = %.2f", b);

if(c>=a && c>=b)

printf("Largest number = %.2f", c);

return 0;

Source Code 2
#include <stdio.h>

int main(){

float a, b, c;

printf("Enter three numbers: ");

scanf("%f %f %f", &a, &b, &c);

if (a>=b)

if(a>=c)

printf("Largest number = %.2f",a);

else

printf("Largest number = %.2f",c);

else

if(b>=c)

printf("Largest number = %.2f",b);

else

printf("Largest number = %.2f",c);

return 0;

Source Code 3

#include <stdio.h>

int main(){

float a, b, c;

printf("Enter three numbers: ");

scanf("%f %f %f", &a, &b, &c);

if(a>=b && a>=c)


printf("Largest number = %.2f", a);

else if(b>=a && b>=c)

printf("Largest number = %.2f", b);

else

printf("Largest number = %.2f", c);

return 0;

Output 1

Enter three numbers: 12.2

13.452

10.193

Largest number = 13.45

4. C program to Find all Roots of a Quadratic equation


Suppose to find roots of a quadratic equation ax2+bx+c=0 where a, b and c are coefficients. This
program will ask the coefficients: a, b and c from user and displays the roots.

#include <stdio.h>

#include <math.h> /* This is needed to use sqrt() function.*/

int main()

float a, b, c, determinant, r1,r2, real, imag;

printf("Enter coefficients a, b and c: ");

scanf("%f%f%f",&a,&b,&c);

determinant=b*b-4*a*c;

if (determinant>0)

r1= (-b+sqrt(determinant))/(2*a);

r2= (-b-sqrt(determinant))/(2*a);

printf("Roots are: %.2f and %.2f",r1 , r2);

}
else if (determinant==0)

r1 = r2 = -b/(2*a);

printf("Roots are: %.2f and %.2f", r1, r2);

else

real= -b/(2*a);

imag = sqrt(-determinant)/(2*a);

printf("Roots are: %.2f+%.2fi and %.2f-%.2fi", real, imag, real, imag);

return 0;

Output 1

Enter coefficients a, b and c: 2.3

5.6

Roots are: -0.87+1.30i and -0.87-1.30i

Output 2

Enter coefficients a, b and c: 4

Roots are: 0.00 and -0.25

C Program to Display Prime Numbers between Intervals by Making Function


This program takes two positive integers from user and displays all prime numbers between these
two intervals. To perform this task, user-defined function is created which will check whether a
number is prime or not.

In this program, all numbers between two intervals is passed to function int check_prime(int
num) using for loop. This function checks whether a number is prime or not. If the number is
prime it returns 1 if not it return 0.
#include<stdio.h>

int check_prime(int num);

int main(){

int n1,n2,i,flag;

printf("Enter two numbers(intervals): ");

scanf("%d %d",&n1, &n2);

printf("Prime numbers between %d and %d are: ", n1, n2);

for(i=n1+1;i<n2;++i)

flag=check_prime(i);

if(flag==0)

printf("%d ",i);

return 0;

int check_prime(int num) /* User-defined function to check prime number*/

int j,flag=0;

for(j=2;j<=num/2;++j){

if(num%j==0){

flag=1;

break;

return flag;

Output:
Enter two numbers(intervals): 10

30

Prime numbers between 10 and 30 are: 11 13 17 19 23 29

C Program to Check Prime and Armstrong Number by Making Function


In this program, user is asked to enter a positive integer and a character either 'p' or 'a'. If user
enters p then, this program checks whether that number is prime or not and if user enters a then,
this program checks whether that number is an Armstrong number or not. To perform this task,
two user-defined functions are defined to check prime number and Armstrong number.
#include<stdio.h>

int prime(int n);

int armstrong(int n);

int main()

char c;

int n,temp=0;

printf("Eneter a positive integer: ");

scanf("%d",&n);

printf("Enter P to check prime and A to check Armstrong number: ");

c=getche();

if(c=='p'|| c=='P')

temp=prime(n);

if(temp==1)

printf("\n%d is a prime number.", n);

else

printf("\n%d is not a prime number.", n);

if(c=='a'|| c=='A')

temp=armstrong(n);
if(temp==1)

printf("\n%d is an Armstrong number.", n);

else

printf("\n%d is not an Armstrong number.",n);

return0;

int prime(int n)

int i, flag=1;

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

if(n%i==0)

flag=0;

break;

return flag;

int armstrong(int n)

int num=0, temp, flag=0;

temp=n;

while(n!=0)

num+=(n%10)*(n%10)*(n%10);

n/=10;
}

if(num==temp)

flag=1;

return flag;

}
Output:
Eneter a positive integer: 371

Enter P to check prime and A to check Armstrong number: p

371 is not a prime number.


Sum of Two Prime Numbers
This program takes a positive integer from user and checks whether that number can be expressed
as the sum of two prime numbers. If that number can be expressed as sum of two prime numbers
then, that number is expressed as sum of two prime numbers in output. To perform this task, a
user-defined function is created to check prime number.
#include<stdio.h>

int prime(int n);

int main()

int n, i, flag=0;

printf("Enter a positive integer: ");

scanf("%d",&n);

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

if(prime(i)!=0)

if( prime(n-i)!=0)

printf("%d = %d + %d\n", n, i, n-i);

flag=1;

}
}

if(flag==0)

printf("%d can't be expressed as sum of two prime numbers.",n);

return0;

int prime(int n)/* Function to check prime number */

int i, flag=1;

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

if(n%i==0)

flag=0;

return flag;

}
Output:
Enter a positive integer: 34

34 = 3 + 31

34 = 5 + 29

34 = 11 + 23

34 = 17 + 17
C program to Find Sum of Natural Numbers using Recursion.
In this program, user is asked to enter a positive integer and sum of natural numbers up to that
integer is displayed by this program. Suppose, user enters 5 then,
Sum will be equal to 1+2+3+4+5 = 15
#include<stdio.h>

int add(int n);

int main()

int n;

printf("Enter an positive integer: ");

scanf("%d",&n);
printf("Sum = %d",add(n));

return0;

int add(int n)

if(n!=0)

return n+add(n-1);/* recursive call */

}
Output:
Enter an positive integer: 10

Sum = 210
C program to Calculate Factorial of a Number Using Recursion
This program takes a positive integer from user and calculates the factorial of that number. Instead
of loops to calculate factorial, this program uses recursive function to calculate the factorial of a
number.
#include<stdio.h>

int factorial(int n);

int main()

int n;

printf("Enter an positive integer: ");

scanf("%d",&n);

printf("Factorial of %d = %ld", n, factorial(n));

return0;

int factorial(int n)

if(n!=1)

return n*factorial(n-1);

}
Output:
Enter an positive integer: 6
Factorial of 6 = 720
C program to Reverse a Sentence Using Recusrion
This program takes a sentence from user and reverses that sentence using recursion. This program
does not use string to reverse the sentence or store the sentence.
This program prints "Enter a sentence: " then, Reverse() function is called. This function stores the
first letter entered by user and stores in variable c. If that variable is other than '\n' [ enter
character] then, again Reverse()function is called. Don't assume this Reverse() function and
the Reverse() function before is same although they both have same name. Also, the variables are
also different, i.e., c variable in both functions are also different. Then, the second character is
stored in variable c of second Reverse function. This process goes on until user enters '\n'. When,
user enters '\n', the last function Reverse() function returns to second last Reverse() function and
prints the last character. Second last Reverse() function returns to the third last Reverse() function and
prints second last character. This process goes on and the final output will be the reversed
sentence.
#include<stdio.h>

voidReverse();

int main()

printf("Enter a sentence: ");

Reverse();

return0;

voidReverse()

char c;

scanf("%c",&c);

if( c !='\n')

Reverse();

printf("%c",c);

}
Output:
Enter a sentence: margorp emosewa

awesome program
C program to Calculate the Power of a Number Using Recursion
This program takes two integers from user ( base number and a exponent) and calculates the
power. Instead of using loops to calculate power, this program uses recursion to calculate the
power of a number.

#include<stdio.h>

int power(int n1,int n2);

int main()

intbase, exp;

printf("Enter base number: ");

scanf("%d",&base);

printf("Enter power number(positive integer): ");

scanf("%d",&exp);

printf("%d^%d = %d",base, exp, power(base, exp));

return0;

int power(intbase,int exp)

if( exp!=1)

return(base*power(base,exp-1));

}
Output:
Enter base number: 3

Enter power number(positive integer): 3

3^3 = 27
C Program to Calculate Average Using Arrays
This program takes n number of element from user(where, n is specified by user), stores data in an
array and calculates the average of those numbers.
#include<stdio.h>

int main(){

int n, i;
float num[100], sum=0.0, average;

printf("Enter the numbers of data: ");

scanf("%d",&n);

while(n>100|| n<=0)

printf("Error! number should in range of (1 to 100).\n");

printf("Enter the number again: ");

scanf("%d",&n);

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

printf("%d. Enter number: ",i+1);

scanf("%f",&num[i]);

sum+=num[i];

average=sum/n;

printf("Average = %.2f",average);

return0;

}
Output

C Program to Find Largest Element of an Array


This program takes n number of element from user(where, n is specified by user) and stores data in
an array. Then, this program displays the largest element of that array using loops.
#include<stdio.h>

int main(){
int i,n;

float arr[100];

printf("Enter total number of elements(1 to 100): ");

scanf("%d",&n);

printf("\n");

for(i=0;i<n;++i)/* Stores number entered by user. */

printf("Enter Number %d: ",i+1);

scanf("%f",&arr[i]);

for(i=1;i<n;++i)/* Loop to store largest number to arr[0] */

if(arr[0]<arr[i])/* Change < to > if you want to find smallest element*/

arr[0]=arr[i];

printf("Largest element = %.2f",arr[0]);

return0;

Output

C Program to Create a Linked List & Display the Elements in the List
This C Program creates a linked list &display the elements in the list. Linked list is an ordered set
of data elements, each containing a link to its successor. This program is to create a linked list and
display all the elements present in the created list.

Here is source code of the C program to create a linked list & display the elements in the list. The
C program is successfully compiled and run on a Linux system. The program output is also shown
below.

/*

C program to create a linked list and display the elements in the list

*/

#include <stdio.h>

#include <malloc.h>

#include <stdlib.h>

void main()

ruct node

t num;

ruct node *ptr;

pedefstruct node NODE;

NODE *head,*first,*temp =0;

t count =0;

t choice =1;

first =0;

hile(choice)
head =(NODE *)malloc(sizeof(NODE));

rintf("Enter the data item\n");

anf("%d",&head-> num);

(first !=0)

temp->ptr = head;

temp = head;

se

first = temp = head;

lush(stdin);

rintf("Do you want to continue(Type 0 or 1)?\n");

anf("%d",&choice);

temp->ptr =0;

reset temp to the beginning */

temp = first;

rintf("\n status of the linked list is\n");

hile(temp !=0)

rintf("%d=>", temp->num);

count++;

temp = temp -> ptr;

rintf("NULL\n");
rintf("No. of nodes in the list = %d\n", count);

Output

Enter the data item 5

Do you want to continue(Type 0 or 1)?0

status of the linked list is 5=>NULL

No. of nodes in the list = 1

Enter the data item 5

Do you want to continue(Type 0 or 1)?1

Enter the data item 9

Do you want to continue(Type 0 or 1)?1

Enter the data item 3

Do you want to continue(Type 0 or 1)?0

status of the linked list is

5=>9=>3=>NULL

No. of nodes in the list = 3

C Program to Illustrate the Operations of Singly Linked List

This C Program illustrates the operations of singly linked list. The program does insertion and
removal of elements from any position in the sequence.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 30
 
struct emp_data
{
int empno;
char empName[MAX];
char designation[MAX];
struct emp_data *next;
};
 
struct emp_data *insert(struct emp_data *front,int id,char name[],
char desg[])
{
struct emp_data *newnode;
  newnode =(struct emp_data*)malloc(sizeof(struct emp_data));
  if(newnode == NULL)
{
printf("\n Allocation failed \n");
exit(2);
}
newnode->empno = id;
strcpy(newnode->empName, name);
strcpy(newnode->designation, desg);
newnode->next = front;
front = newnode;
return(front);
}
void printNode(struct emp_data *p)
{
printf("\n Employee Details...\n");
printf("\n Emp No : %d", p->empno);
printf("\n Name : %s", p->empName);
printf("\n Designation : %s\n", p->designation);
printf("-------------------------------------\n");
}
struct emp_data* deleteNode(struct emp_data *front,int id)
{
struct emp_data *ptr;
struct emp_data *bptr;
 
if(front->empno == id)
{
ptr = front;
printf("\n Node deleted:");
printNode(front);
front = front->next;
free(ptr);
return(front);
}
for(ptr = front->next, bptr = front; ptr != NULL; ptr = ptr->next,
bptr = bptr->next)
{
if(ptr->empno == id)
{
printf("\n Node deleted:");
printNode(ptr);
bptr->next = ptr->next;
free(ptr);
return(front);
}
}
printf("\n Employee Number %d not found ", id);
return(front);
}
void search(struct emp_data *front,int key)
{
struct emp_data *ptr;
 
for(ptr = front; ptr != NULL; ptr = ptr -> next)
{
if(ptr->empno == key)
{
printf("\n Key found:");
printNode(ptr);
return;
}
}
printf("\n Employee Number %d not found ", key);
}
void display(struct emp_data *front)
{
struct emp_data *ptr;
 
for(ptr = front; ptr != NULL; ptr = ptr->next)
{
printNode(ptr);
}
}
void menu()
{
printf("---------------------------------------------\n");
printf("Press 1 to INSERT a node into the list \n");
printf("Press 2 to DELETE a node from the list \n");
printf("Press 3 to DISPLAY the list \n");
printf("Press 4 to SEARCH the list \n");
printf("Press 5 to EXIT \n");
printf("---------------------------------------------\n");
}
char option()
{
char choice;
 
printf("\n\n>> Enter your choice: ");
switch(choice=getche())
{
case'1':
case'2':
case'3':
case'4':
case'5':return(choice);
default:printf("\n Invalid choice.");
}
return choice;
}
void main()
{
struct emp_data *linkList;
char name[21], desig[51];
char choice;
int eno;
 
linkList = NULL;
printf("\n Welcome to demonstration of singly linked list \n");
menu();
do
{
/* choose oeration to be performed */
choice = option();
switch(choice)
{
case'1':
printf("\n Enter the Employee Number : ");scanf("%d",&eno);
printf("Enter the Employee name : ");fflush(stdin);
gets(name);
printf("Enter the Employee Designation : ");gets(desig);
linkList = insert(linkList, eno, name, desig);break;
case'2':
printf("\n\n Enter the employee number to be deleted: ");scanf("%d",&eno);
linkList = deleteNode(linkList, eno);break;
case'3':
if(linkList == NULL)
{
printf("\n List empty.");
break;
}
display(linkList);
break;
case'4':
printf("\n\n Enter the employee number to be searched: ");
scanf("%d",&eno);
search(linkList, eno);
break;
case'5':break;
}
}while(choice !='5');
}

Output:

Welcome to demonstration of singly linked list

---------------------------------------------
Press 1 to INSERT a node into the list

Press 2 to DELETE a node from the list

Press 3 to DISPLAY the list

Press 4 to SEARCH the list

Press 5 to EXIT

---------------------------------------------

>> Enter your choice: 1

Enter the Employee Number : 12

Enter the Employee name : ram

Enter the Employee Designation : HR

>> Enter your choice: 3

Employee Details...

Emp No : 12

Name : ram

Designation : HR

-------------------------------------

>> Enter your choice:

Invalid choice.

>> Enter your choice: 4

Enter the employee number to be searched: 12

Key found:

Employee Details...

Emp No : 12

Name : ram
Designation : HR

-------------------------------------

>> Enter your choice:

Invalid choice.

>> Enter your choice: 2

Enter the employee number to be deleted: 12

Node deleted:

Employee Details...

Emp No : 12

Name : ram

Designation : HR

-------------------------------------

>> Enter your choice:

Invalid choice.

>> Enter your choice: 4

Enter the employee number to be searched: 1

Employee Number 1 not found

>> Enter your choice:

Invalid choice.

>> Enter your choice: 5

C Program to Search for an Element in the Linked List using Recursion

This C Program uses recursive function & search for an element in a linked list. A linked list is an
ordered set of data elements, each containing a link to its successor.

#include <stdio.h>

#include <stdlib.h>

struct node
{

int a;

struct node *next;

};

 void generate(struct node **,int);

void search(struct node *,int,int);

void delete(struct node **);

 int main()

struct node *head;

int key, num;

printf("Enter the number of nodes: ");

scanf("%d",&num);

generate(&head, num);

printf("\nEnter key to search: ");

scanf("%d",&key);

search(head, key, num);

delete(&head);

 void generate(struct node **head,int num)

int i;

struct node *temp;

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

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

temp->a =rand()% num;


printf("%d ", temp->a);

if(*head == NULL)

*head = temp;

(*head)->next = NULL;

else

temp->next =*head;

*head = temp;

}}}

 void search(struct node *head,int key,int index)

if(head->a == key)

printf("Key found at Position: %d\n", index);

if(head->next == NULL)

return;

search(head->next, key, index -1);

 void delete(struct node **head)

struct node *temp;

while(*head != NULL)

{
temp =*head;

*head =(*head)->next;

free(temp);

}}

Output:

Enter the number of nodes: 6


1 4 3 1 5 1
Enter key to search: 1
Key found at Position: 6
Key found at Position: 4
Key found at Position: 1
C Program to Implement a Stack using Linked List

This C Program implement a stack using linked list. Stack is a type of queue that in practice is
implemented as an area of memory that holds all local variables and parameters used by any
function, and remembers the order in which functions are called so that function returns occur
correctly. Each time a function is called, its local variables and parameters are “pushed onto” the
stack. When the function returns,these locals and parameters are “popped.” Because of this, the
size of a program’s stack fluctuates constantly as the program is running, but it has some
maximum size. stack is as a last in, first out (LIFO) abstract data type and linear data structure.
Linked list is a data structure consisting of a group of nodes which together represent a sequence.
Here we need to apply the application of linkedlist to perform basic operations of stack.

#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)
{
case1:
printf("Enter data : ");
scanf("%d",&no);
push(no);
break;
case2:
pop();
break;
case3:
if(top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case4:
empty();
break;
case5:
exit(0);
case6:
display();
break;
case7:
stack_count();
break;
case8:
destroy();
break;
default:
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
}
 /* Create empty stack */
void create()
{
top = NULL;
}
 /* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}
 /* Push data into stack */
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++;
}
 /* Display stack elements */
void display()
{
top1 = top;
 
if(top1 == NULL)
{
printf("Stack is empty");
return;
}
 
while(top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
 /* Pop Operation on stack */
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--;
}
 /* Return top element */
int topelement()
{
return(top->info);
}
 /* Check if stack is empty or not */
void empty()
{
if(top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
 /* Destroy entire stack */
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;
}
Output:
1 - Push

2 - Pop

3 - Top

4 - Empty

5 - Exit

6 - Dipslay
7 - Stack Count

8 - Destroy stack

Enter choice : 1

Enter data : 56

Enter choice : 1

Enter data : 80

Enter choice : 2

Popped value : 80

Enter choice : 3

Top element : 56

Enter choice : 1

Enter data : 78

Enter choice : 1

Enter data : 90

Enter choice : 6

907856

Enter choice : 7

No. of elements in stack : 3

Enter choice : 8

All stack elements destroyed


Enter choice : 4

Stack is empty

Enter choice : 5

C Program Count the Number of Occurrences of an Element in the Linked List using
Recursion

This C Program uses recursive function & finds the occurrence for an element in an unsorted list. The
user enters the element need to be counted.

#include <stdio.h>

 void occur(int[],int,int,int,int*);

 int main()

int size, key, count =0;

int list[20];

int i;

  printf("Enter the size of the list: ");

scanf("%d",&size);

printf("Printing the list:\n");

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

list[i]=rand()% size;

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

printf("\nEnter the key to find it's occurence: ");

scanf("%d",&key);

occur(list, size,0, key,&count);

printf("%d occurs for %d times.\n", key, count);

return0;

}
 void occur(int list[],int size,int index,int key,int*count)

if(size == index)

return;

if(list[index]== key)

*count +=1;

occur(list, size, index +1, key, count);

Output:

Enter the size of the list: 7

Printing the list:

1 4 2 5 1 3 3

Enter the key to find it's occurence: 3

3 occurs for 2 times.

C Program to Implement Queue Data Structure using Linked List

This C Program implements queue using linked list. Queue is a particular kind of abstract data
type or collection in which the entities in the collection are kept in order and the principal (or only)
operations on the collection are the addition of entities to the rear terminal position, known as
enqueue, and removal of entities from the front terminal position, known as dequeue. This makes
the queue a First-In-First-Out (FIFO) data structure. Linked list is a data structure consisting of a
group of nodes which together represent a sequence. Here we need to apply the application of
linkedlist to perform basic operations of queue.

#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;

/* Create an empty queue */

void create()

front = rear = NULL;

/* Returns queue size */

void queuesize()

printf("\n Queue size : %d", count);

/* Enqueing the queue */

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++;

/* Displaying the queue elements */

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);

/* Dequeing the queue */

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--;

/* Returns the front element of queue */

int frontelement()

if ((front != NULL) && (rear != NULL))

return(front->info);

else

return 0;

/* Display if queue is empty or not */

void empty()

if ((front == NULL) && (rear == NULL))

printf("\n Queue empty");

else

printf("Queue not empty");

Output:

1 - Enque
2 - Deque

3 - Front element

4 - Empty

5 - Exit

6 - Display

7 - Queue size

Enter choice : 1

Enter data : 14

Enter choice : 1

Enter data : 85

Enter choice : 1

Enter data : 38

Enter choice : 3

Front element : 14

Enter choice : 6

14 85 38

Enter choice : 7

Queue size : 3

Enter choice : 2

Dequed value : 14

Enter choice : 6

85 38

Enter choice : 7
Queue size : 2

Enter choice : 4

Queue not empty

Enter choice : 5

C Program to Implement a Doubly Linked List & provide Insertion, Deletion & Display
Operations

This C Program implement a doubly linked list & provide insertion, deletion & display operations.
Doubly linked list is a linked data structure that consists of a set of sequentially linked records
called nodes. Each node contains two fields, called links, that are references to the previous and to
the next node in the sequence of nodes. The beginning and ending nodes’ previous and next links,
respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate
traversal of the list. Here we need to preform insertion, deletion and display all the modes of given
doubly linked list.

#include <stdio.h>
#include <stdlib.h>
 
struct node
{
struct node *prev;
int n;
struct node *next;
}*h,*temp,*temp1,*temp2,*temp4;
 
void insert1();
void insert2();
void insert3();
void traversebeg();
void traverseend(int);
void sort();
void search();
void update();
void delete();
 
int count =0;
 
void main()
{
int ch;
 
h = NULL;
temp = temp1 = NULL;
 
printf("\n 1 - Insert at beginning");
printf("\n 2 - Insert at end");
printf("\n 3 - Insert at position i");
printf("\n 4 - Delete at i");
printf("\n 5 - Display from beginning");
printf("\n 6 - Display from end");
printf("\n 7 - Search for element");
printf("\n 8 - Sort the list");
printf("\n 9 - Update an element");
printf("\n 10 - Exit");
 
while(1)
{
printf("\n Enter choice : ");
scanf("%d",&ch);
switch(ch)
{
case1:
insert1();
break;
case2:
insert2();
break;
case3:
insert3();
break;
case4:
delete();
break;
case5:
traversebeg();
break;
case6:
temp2 = h;
if(temp2 == NULL)
printf("\n Error : List empty to display ");
else
{
printf("\n Reverse order of linked list is : ");
traverseend(temp2->n);
}
break;
case7:
search();
break;
case8:
sort();
break;
case9:
update();
break;
case10:
exit(0);
default:
printf("\n Wrong choice menu");
}
}
}
 
/* TO create an empty node */
void create()
{
int data;
 
temp =(struct node *)malloc(1*sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
printf("\n Enter value to node : ");
scanf("%d",&data);
temp->n = data;
count++;
}
 
/* TO insert at beginning */
void insert1()
{
if(h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp->next = h;
h->prev = temp;
h = temp;
}
}
 
/* To insert at end */
void insert2()
{
if(h == NULL)
{
create();
h = temp;
temp1 = h;
}
else
{
create();
temp1->next = temp;
temp->prev = temp1;
temp1 = temp;
}
}
 
/* To insert at any position */
void insert3()
{
int pos, i =2;
 
printf("\n Enter position to be inserted : ");
scanf("%d",&pos);
temp2 = h;
 
if((pos <1)||(pos >= count +1))
{
printf("\n Position out of range to insert");
return;
}
if((h == NULL)&&(pos !=1))
{
printf("\n Empty list cannot insert other than 1st position");
return;
}
if((h == NULL)&&(pos ==1))
{
create();
h = temp;
temp1 = h;
return;
}
else
{
while(i < pos)
{
temp2 = temp2->next;
i++;
}
create();
temp->prev = temp2;
temp->next = temp2->next;
temp2->next->prev = temp;
temp2->next = temp;
}
}
 
/* To delete an element */
void delete()
{
int i =1, pos;
 
printf("\n Enter position to be deleted : ");
scanf("%d",&pos);
temp2 = h;
 
if((pos <1)||(pos >= count +1))
{
printf("\n Error : Position out of range to delete");
return;
}
if(h == NULL)
{
printf("\n Error : Empty list no elements to delete");
return;
}
else
{
while(i < pos)
{
temp2 = temp2->next;
i++;
}
if(i ==1)
{
if(temp2->next == NULL)
{
printf("Node deleted from list");
free(temp2);
temp2 = h = NULL;
return;
}
}
if(temp2->next == NULL)
{
temp2->prev->next = NULL;
free(temp2);
printf("Node deleted from list");
return;
}
temp2->next->prev = temp2->prev;
if(i !=1)
temp2->prev->next = temp2->next;/* Might not need this statement if i == 1 check */
if(i ==1)
h = temp2->next;
printf("\n Node deleted");
free(temp2);
}
count--;
}
 
/* Traverse from beginning */
void traversebeg()
{
temp2 = h;
 
if(temp2 == NULL)
{
printf("List empty to display \n");
return;
}
printf("\n Linked list elements from begining : ");
 
while(temp2->next != NULL)
{
printf(" %d ", temp2->n);
temp2 = temp2->next;
}
printf(" %d ", temp2->n);
}
 
/* To traverse from end recursively */
void traverseend(int i)
{
if(temp2 != NULL)
{
i = temp2->n;
temp2 = temp2->next;
traverseend(i);
printf(" %d ", i);
}
}
 
/* To search for an element in the list */
void search()
{
int data, count =0;
temp2 = h;
 
if(temp2 == NULL)
{
printf("\n Error : List empty to search for data");
return;
}
printf("\n Enter value to search : ");
scanf("%d",&data);
while(temp2 != NULL)
{
if(temp2->n == data)
{
printf("\n Data found in %d position",count +1);
return;
}
else
temp2 = temp2->next;
count++;
}
printf("\n Error : %d not found in list", data);
}
 
/* To update a node value in the list */
void update()
{
int data, data1;
 
printf("\n Enter node data to be updated : ");
scanf("%d",&data);
printf("\n Enter new data : ");
scanf("%d",&data1);
temp2 = h;
if(temp2 == NULL)
{
printf("\n Error : List empty no node to update");
return;
}
while(temp2 != NULL)
{
if(temp2->n == data)
{
 
temp2->n = data1;
traversebeg();
return;
}
else
temp2 = temp2->next;
}
 
printf("\n Error : %d not found in list to update", data);
}
 
/* To sort the linked list */
void sort()
{
int i, j, x;
 
temp2 = h;
temp4 = h;
 
if(temp2 == NULL)
{
printf("\n List empty to sort");
return;
}
 
for(temp2 = h; temp2 != NULL; temp2 = temp2->next)
{
for(temp4 = temp2->next; temp4 != NULL; temp4 = temp4->next)
{
if(temp2->n > temp4->n)
{
x = temp2->n;
temp2->n = temp4->n;
temp4->n = x;
}
}
}
traversebeg();
}

Output:
1 - Insert at beginning

2 - Insert at end

3 - Insert at position i

4 - Delete at i

5 - Display from beginning

6 - Display from end

7 - Search for element

8 - Sort the list

9 - Update an element

10 - Exit

Enter choice : 1

Enter value to node : 10

Enter choice : 2

Enter value to node : 50

Enter choice : 4

Enter position to be deleted : 1

Node deleted
Enter choice : 1

Enter value to node : 34

Enter choice : 3

Enter position to be inserted : 2

Enter value to node : 13

Enter choice : 4

Enter position to be deleted : 4

Error : Position out of range to delete

Enter choice : 1

Enter value to node : 15

Enter choice : 1

Enter value to node : 67

Enter choice : 3

Enter position to be inserted : 2

Enter value to node : 34


 

Enter choice : 4

Enter position to be deleted : 3

Node deleted

Enter choice : 7

Enter value to search : 15

Error : 15 not found in list

Enter choice : 8

Linked list elements from begining : 1334345067

Enter choice : 9

Enter node data to be updated : 45

Enter new data : 89

Error : 45 not found in list to update

Enter choice : 9

Enter node data to be updated : 50

Enter new data : 90

Enter choice : 5

 
Linked list elements from begining : 1334349067

Enter choice : 6

Reverse order of linked list is : 6790343413

Enter choice : 7

Enter value to search : 90

Data found in4 position

Enter choice : 8

Linked list elements from begining : 1334346790

Enter choice : 7

Enter value to search : 90

Data found in5 position

Enter choice : 9

Enter node data to be updated : 34

Enter new data : 56

Linked list elements from begining : 1356346790

Enter choice : 10

C Program to Add Corresponding Positioned Elements of 2 Linked Lists

This C Program adds the corresponding positioned elements of 2 linked lists and display.
#include <stdio.h>

#include <stdlib.h>

#include <ctype.h>

struct node

int num;

struct node *next;

};

 int feednumber(struct node **);

struct node *addlist(struct node *,struct node *,int,int);

void release(struct node **);

void display(struct node *);

 int main()

struct node *p = NULL;

struct node *q = NULL;

struct node *res = NULL;

int pcount =0, qcount =0;

  printf("Enter first number\n");

pcount = feednumber(&p);

printf("Enter second number\n");

qcount = feednumber(&q);

printf("Displaying list1: ");

display(p);

printf("Displaying list2: ");

display(q);

res = addlist(p, q, pcount, qcount);


printf("Displaying the resulting list: ");

display(res);

release(&p);

release(&q);

release(&res);

  return0;

 /*Function to create nodes of numbers*/

int feednumber(struct node **head)

char ch, dig;

int count =0;

struct node *temp,*rear = NULL;

  ch =getchar();

while(ch !='\n')

dig =atoi(&ch);

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

temp->num = dig;

temp->next = NULL;

count++;

if((*head)== NULL)

*head = temp;

rear = temp;

else

{
rear->next = temp;

rear = rear->next;

ch =getchar();

  return count;

 /*Function to display the list of numbers*/

void display (struct node *head)

while(head != NULL)

printf("%d", head->num);

head = head->next;

printf("\n");

 /*Function to free the allocated list of numbers*/

void release (struct node **head)

struct node *temp =*head;

while((*head)!= NULL)

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

free(temp);

temp =*head;

}
}

 /*Function to add the list of numbers and store them in 3rd list*/

struct node *addlist(struct node *p,struct node *q,int pcount,int qcount)

struct node *ptemp,*qtemp,*result = NULL,*temp;

int i, carry =0;

while(pcount !=0&& qcount !=0)

ptemp = p;

qtemp = q;

for(i =0; i < pcount -1; i++)

ptemp = ptemp->next;

for(i =0; i < qcount -1; i++)

qtemp = qtemp->next;

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

temp->num = ptemp->num + qtemp->num + carry;

carry = temp->num /10;

temp->num = temp->num %10;

temp->next = result;

result = temp;

pcount--;

qcount--;

}
/*both or one of the 2 lists have been read completely by now*/

while(pcount !=0)

ptemp = p;

for(i =0; i < pcount -1; i++)

ptemp = ptemp->next;

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

temp->num = ptemp->num + carry;

carry = temp->num /10;

temp->num = temp->num %10;

temp->next = result;

result = temp;

pcount--;

while(qcount !=0)

qtemp = q;

for(i =0; i < qcount -1; i++)

qtemp = qtemp->next;

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

temp->num = qtemp->num + carry;

carry = temp->num /10;

temp->num = temp->num %10;

temp->next = result;
result = temp;

qcount--;

  return result;

Output:

Enter first number12345


Enter second number5678903
Displaying list1: 12345
Displaying list2: 5678903
Displaying the resulting list: 5691248
C Program to check whether 2 Lists are Same
This C Program checks whether 2 lists are the same. The lists are said to be same if they contain
same elements at same position.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};

void feedmember(struct node **);


int compare (struct node *, struct node *);
void release(struct node **);

int main()
{
struct node *p = NULL;
struct node *q = NULL;
int result;

printf("Enter data into first list\n");


feedmember(&p);
printf("Enter data into second list\n");
feedmember(&q);
result = compare(p, q);
if (result == 1)
{
printf("The 2 list are equal.\n");
}
else
{
printf("The 2 lists are unequal.\n");
}
release (&p);
release (&q);

return 0;
}

int compare (struct node *p, struct node *q)


{
while (p != NULL && q != NULL)
{
if (p->num != q-> num)
{
return 0;
}
else
{
p = p->next;
q = q->next;
}
}
if (p != NULL || q != NULL)
{
return 0;
}
else
{
return 1;
}
}

void feedmember (struct node **head)


{
int c, ch;
struct node *temp;

do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = *head;
*head = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
}while (ch != 0);
printf("\n");
}

void release (struct node **head)


{
struct node *temp = *head;

while ((*head) != NULL)


{
(*head) = (*head)->next;
free(temp);
temp = *head;
}
}
Output:
Enter data into first list
Enter number: 12
Do you wish to continue [1/0]: 1
Enter number: 3
Do you wish to continue [1/0]: 1
Enter number: 28
Do you wish to continue [1/0]: 1
Enter number: 9
Do you wish to continue [1/0]: 0
 
Enter data into second list
Enter number: 12
Do you wish to continue [1/0]: 1
Enter number: 3
Do you wish to continue [1/0]: 1
Enter number: 28
Do you wish to continue [1/0]: 1
Enter number: 9
Do you wish to continue [1/0]: 0
 
The 2 list are equal.

You might also like