Posts

Data Structures - Linked List | Insertion at the Nth position

Image
In the previous post we had performed the  Insertion at the beginning operation in Linked List , which went well when we wanted to insert the element in an empty list or at the beginning of a filled list. In this post we would look at the Insertion of elements at the Nth position. Take a look at the following diagram! The above diagram describes what we are going to do. To be specific: We will be creating a Node (temporary node) that we want to insert into the linked list. We will also create another node that will store the information of the previous node( the node after which we are going to add our new node). Next, we will traverse through the linked list until the node just before the Nth node. In the new node we will assign its next pointer to the next pointer of the previous node. Also we will update the next pointer of previous node to point to the new node. At last we are going to print the list. While performing the above steps keep in mind that init...

Data Structures - Linked List | Insertion in the beginning

Image
Why do we use Linked List instead of Arrays ?  Arrays have the following limitations : Size of the array is fixed. We have to define the upper limit of the elements. The memory allocation of the array is done according to the maximum size of the array irrespective of the usage of the memory. Insertion of the new element is difficult because we have to create new room for the element and the already present elements must be shifted. What is a Linked List? A linked list is a linear data structure, in which the elements are not stored  at contiguous memory locations. The elements in the linked list are linked using pointers as shown in the below image: Let's take a closer look. Linked Lists basically consists of Nodes which are connected to each other and are stored in non-contiguous memory. If we look at a single node we would find that it contains two blocks. The first block contains the data and the second block contains a pointer to the ne...

Array Rotation | C++

Image
Problem Statement: The problem statement basically gives you an array of size n and asks you to rotate it k times towards the right or the left Example: The Solution: The following steps are going to describe what we are going to do in out code   Create two integers n and k which represent the size of the array and the number of rotations respectively. Create an array of size n and insert values in it Use a while loop to iterate for k times i.e. the number of rotations Inside the while loop, create a variable temp and store the first element in it. Use a for loop to scan all the elements of the array and in it use a[i] = a[i+1]; (i.e. the first element will be replaced by the second, the second by the third and so on). Finally print the array to display the output. Here's the code: Output: