C Programming Code Examples
C > Linked Lists Code Examples
Program to Find Intersection & Union of 2 Linked Lists
/* Program to Find Intersection & Union of 2 Linked Lists
This C Program finds the intersection and union of 2 linked lists. Intersection is a set of elements that are common in both lists while union is a set of all unique elements in both the lists */
#include <stdio.h>
#include <stdlib.h>
struct node
{
int j;
struct node *next;
};
void create(struct node **);
void findunion(struct node *, struct node *, struct node **);
void findintersect(struct node *, struct node *, struct node **);
void display(struct node *);
void release(struct node **);
int main()
{
struct node *phead, *qhead, *intersect, *unionlist;
phead = qhead = intersect = unionlist = NULL;
printf("Enter elements in the list 1\n");
create(&phead);
printf("\nEnter elements in the list 2\n");
create(&qhead);
findunion(phead, qhead, &unionlist);
findintersect(phead, qhead, &intersect);
printf("\nDisplaying list 1:\n");
display(phead);
printf("Displaying list 2:\n");
display(qhead);
printf("Displaying the union of the 2 lists:\n");
display(unionlist);
printf("Displaying the intersection of the 2 lists:\n");
if (intersect == NULL)
{
printf("Null\n");
}
else
{
display(intersect);
}
release(&phead);
release(&qhead);
release(&unionlist);
release(&intersect);
return 0;
}
void findintersect(struct node *p, struct node *q, struct node **intersect)
{
struct node *ptemp, *qtemp, *itemp, *irear, *ifront;
ptemp = p;
while (ptemp != NULL)
{
qtemp = q;
ifront = *intersect;
while (qtemp != NULL && ptemp->j != qtemp->j)
{
qtemp = qtemp->next;
}
if (qtemp != NULL)
{
if (ifront != NULL)
{
if (ifront->j == qtemp->j)
{
ptemp = ptemp->next;
continue;
}
ifront = ifront->next;
}
itemp = (struct node *)malloc(sizeof(struct node));
itemp->j = qtemp->j;
itemp->next = NULL;
if (*intersect == NULL)
{
*intersect = itemp;
}
else
{
irear->next = itemp;
}
irear = itemp;
}
ptemp = ptemp->next;
}
}
void findunion(struct node *p, struct node *q, struct node **unionlist)
{
struct node *utemp, *ufront, *urear;
int flag = 0;
while (p != NULL)
{
ufront = *unionlist;
while (ufront != NULL)
{
if (ufront->j == p->j)
{
flag = 1;
}
ufront = ufront->next;
}
if (flag)
{
flag = 0;
}
else
{
utemp = (struct node *)malloc(sizeof(struct node));
utemp->j = p->j;
utemp->next = NULL;
if (*unionlist == NULL)
{
*unionlist = utemp;
}
else
{
urear->next = utemp;
}
urear = utemp;
}
p = p->next;
}
while (q != NULL)
{
ufront = *unionlist;
while (ufront != NULL)
{
if (ufront->j == q->j)
{
flag = 1;
}
ufront = ufront->next;
}
if (flag)
{
flag = 0;
}
else
{
utemp = (struct node *)malloc(sizeof(struct node));
utemp->j = q->j;
utemp->next = NULL;
if (*unionlist == NULL)
{
*unionlist = utemp;
}
else
{
urear->next = utemp;
}
urear = utemp;
}
q = q->next;
}
}
void create(struct node **head)
{
struct node *temp, *rear;
int ch, a;
do
{
printf("Enter a number: ");
scanf("%d", &a);
temp = (struct node *)malloc(sizeof(struct node));
temp->j = a;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you want to continue [1/0] ? ");
scanf("%d", &ch);
} while (ch != 0);
}
void display(struct node *head)
{
while (head != NULL)
{
printf("%d ", head->j);
head = head->next;
}
printf("\n");
}
void release(struct node **head)
{
struct node *temp = *head;
while ((*head) != NULL)
{
(*head) = (*head)->next;
free (temp);
temp = *head;
}
}
The free() function in C library allows you to release or deallocate the memory blocks which are previously allocated by calloc(), malloc() or realloc() functions. It frees up the memory blocks and returns the memory to heap. It helps freeing the memory in your program which will be available for later use. In C, the memory for variables is automatically deallocated at compile time. For dynamic memory allocation in C, you have to deallocate the memory explicitly. If not done, you may encounter out of memory error.
The if...else statement executes two different codes depending upon whether the test expression is true or false. Sometimes, a choice has to be made from more than 2 possibilities. The if...else ladder allows you to check between multiple test expressions and execute different statements. In C/C++ if-else-if ladder helps user decide from among multiple options. The C/C++ if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is bypassed. If none of the conditions is true, then the final else statement will be executed.
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.
An expression containing logical operator returns either 0 or 1 depending upon whether expression results true or false. Logical operators are commonly used in decision making in C programming. These operators are used to perform logical operations and used with conditional statements like C if-else statements.
The continue statement in C programming works somewhat like the break statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between. For the for loop, continue statement causes the conditional test and increment portions of the loop to execute. For the while and do...while loops, continue statement causes the program control to pass to the conditional tests.
A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose. To define a union, you must use the union statement in the same way as you did while defining a structure. The union statement defines a new data type with more than one member for your program. The format of the union statement is as follows:
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
Read formatted data from stdin. Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments. The additional arguments should point to already allocated objects of the type specified by their corresponding format specifier within the format string. In C programming, scanf() is one of the commonly used function to take input from the user. The scanf() function reads formatted input from the standard input such as keyboards. The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.
Allocate memory block. Allocates a block of size bytes of memory, returning a pointer to the beginning of the block. The content of the newly allocated block of memory is not initialized, remaining with indeterminate values. If size is zero, the return value depends on the particular library implementation (it may or may not be a null pointer), but the returned pointer shall not be dereferenced. The "malloc" or "memory allocation" method in C is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. It doesn't Iniatialize memory at execution time so that it has initializes each block with the default garbage value initially.
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
The sizeof() operator is commonly used in C. It determines the size of the expression or the data type specified in the number of char-sized storage units. The sizeof() operator contains a single operand which can be either an expression or a data typecast where the cast is data type enclosed within parenthesis. The data type cannot only be primitive data types such as integer or floating data types, but it can also be pointer data types and compound data types such as unions and structs.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
Imagine we have two number 1 and 2 stored in x and j respectively now. If we add x and j (1 + 2) and store it to x then x will become 3 and j is still 2. We subtract j (2) from new value of
if, else, switch, case, default, break, int, float, char, double, long, for, while, do, void, goto, auto, signed, const, extern, register, return, unsigned, continue, enum, sizeof, struct and
Status epilepticus, print help. Extract UTC time from string. Convert UTC to time string. Print help and exit. Convert INT utc value to timestring. Convert STR to INT utc time...
Program stores a sentence entered by user in a file. After termination of this program, you can see a text file program.txt created in the same location where this program is located.
C Program to input binary number from user and convert to hexadecimal number system. Binary Number System is a base 2 number system. Binary number system use only two
In C, A "Pointer" holds the Address of another variable of same type. When a Pointer Holds the address of another pointer then such type of pointer is known as "pointer-to-pointer" or
C Programming example Store information using structures with dynamically memory allocation. This c program asks user to store the value of noOfRecords and allocates the
C Language program Find 'LCM' of a Number using Recursion. The following C Program to use recursion, finds the 'LCM'. An 'LCM' is the 'Lowest Common Multiple' of any 2 numbers.
C Language program code sample input any number and check whether the given number is even or odd using bitwise operator. How to check whether a number is even or odd using