Monday, October 28, 2019

C++: Segregate even and odd nodes in a linked list.

In this C++ tutorial, we will learn how to segregate even and odd nodes in a linked list.

We are given a singly linked list with even and odd nodes at random positions. What we need to do is segregate even and odd nodes such that all the even nodes comes first and then the odd nodes. Below is the code for the algorithm in C++.


Output:

Before segregation- 17 15 8 12 10 5 4 1 7 6
After segregation- 8 12 10 4 6 17 15 5 1 7


Friday, October 18, 2019

C++: Remove all the duplicates from a sorted linked list.

In this C++ tutorial, we will learn how to remove all the duplicate entries from a sorted linked list. Here is the code for the algorithm in C++ :


Output: 9 8 8 8 7 6 6 5 5 5 5 5 5 5 4 3 3 2 1
             After removing the duplicates -
             9 8 7 6 5 4 3 2 1


Sunday, September 29, 2019

C++: Print matrix in counter-clockwise spiral form

We are given a matrix of any dimension and we need to print the matrix elements in counter clockwise direction.


Output: 1 5 9 10 11 12 8 4 3 2 6 7

C++: Find all the unique elements in a matrix

We are given a matrix of any dimension and wee need to print all the elements that are unique i.e appearing only once. So here is the c++ code for the algorithm.

Output:
The unique elements in the matrix are 4 6 9

Explanation:

First, in the 'main' function, we create the matrix 'mat' of size 4 with 16 elements. Then we call the function 'uniqueElement' with the matrix 'mat' as the parameter. Note, at the top of the program, we have defined R(row) as 4 and C(col) as 4.

In the function 'uniqueElement', we first declare a map 'cnt' of integer type. Then we loop through all the elements of the matrix and increment the frequency of all the elements using 'cnt[mat[i][j]++'. After the loop, all the elements in the matrix will be mapped to its corresponding frequency.

After this, we loop through the map 'cnt' and print the elements with frequency 1.

Thursday, September 26, 2019

C++: Turn a matrix by 180 degree.

We are given a matrix of any dimension and we need to turn it by 180 degree. Here is the source code for the algorithm in c++.


Output:  12  11  10  9
               8    7    6   5
               4    3    2    1
             

Wednesday, September 25, 2019

C++: Print a Matrix in Spiral Form

We are given a matrix of any dimension, say 3x3, 4x4 or 4x3, and we are required to print the elements of the matrix in spiral form.


Output: 1 2 3 4 8 12 11 10 9 5 6 7

C++: Rotate Matrix to the right.

Given a square matrix and we need to write a program to rotate the matrix to the right. Here is the code for the program.

Output:
5    1    2    3
9    10   6    4
13   11   7    8
14   15   16   12