Deletion in Singly Linked List in C++.

We have discussed Insertion and Searching a node in a singly Linked List in our previous post. In this post, we are going to discuss the Deletion of a node in a Linked List.


There are multiple situations of deleting a node from a linked list and these are:

  • Deletion of a node from the middle of the list.
Input: 3->8->1->2
Output: 3->8->2
  • Deletion of a node from the end of the list.
Input: 3->8->1->2
Output: 3->8->1
  • Deletion of a node from the beginning of the list.
Input: 3->8->1->2
Output: 8->1->2



Approach for Deletion of a node.

In a singly linked list, deletion is performed by modifying the pointers of the preceding and subsequent nodes to bypass the node to be deleted. Below are the steps to follow:
  • The deletion method takes integer data as an argument and searches the list for the node with the matching data. 
  • If the head node contains the data, the node is deleted and the head is updated to point to the next node. 
  • If the data is found in another node, the pointers of the preceding and subsequent nodes are modified to bypass the node to be deleted, and the node is deleted.

C++ Code to Delete a node from Singly Linked List.

//C++ Program to delete the node from a linked list
#include <iostream>
using namespace std;

struct Node {
  int data;
  Node *next;
};

class SinglyLinkedList {
private:
  Node *head;

public:
  SinglyLinkedList() : head(nullptr) {}

  void insert(int data) {
    Node *newNode = new Node;
    newNode->data = data;
    newNode->next = head;
    head = newNode;
  }

  void deleteNode(int data) {
    //when list is empty
    if (head == nullptr) return;
    //deleting first node of the list
    if (head->data == data) {
      Node *temp = head;
      head = head->next;
      delete temp;
      return;
    }
    //deleting middle or last node of the list
    Node *prev = head;
    Node *curr = head->next;
    while (curr != nullptr && curr->data != data) {
      prev = curr;
      curr = curr->next;
    }
    if (curr == nullptr) return;
    prev->next = curr->next;
    delete curr;
  }

  void printList() {
    Node *temp = head;
    while (temp != nullptr) {
      cout << temp->data << " ";
      temp = temp->next;
    }
    cout << std::endl;
  }
};

int main() {
  SinglyLinkedList list;

  list.insert(10);
  list.insert(20);
  list.insert(30);
  list.insert(40);
  list.insert(50);
  list.printList();
  list.deleteNode(30);
  list.printList();
  return 0;
}
Output:
50 40 30 20 10
50 40 20 10
  • Time Complexity: O(n)
  • Space Complexity: O(1)

Types of Recursion in C++ with Examples

Recursion and its type in C++

Recursion is a process in which a function calls itself directly or indirectly to solve a problem. In this article, we will learn Recursion in C++ and its implementation.

Syntax:

int fun()
{
   ....
   fun()
}

Recursion allows the function to repeat a specific action until a specific condition is met and the function stops calling itself when the specific condition is met that stopping condition is also known as the base condition.  

Let's understand recursion with one standard example: finding the factorial of a given number. 

C++ Program to find the Factorial of a number.

#include<iostream>
using namespace std;

//function to find factorial
int factorial(int n) {
    if (n == 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main()
{
    int num;

    cout<<"Enter a number: ";
    cin>>num;
    cout<<"Factorial of given number: "<<factorial(num);

    return 0;
}
Output:
Enter a number: 5
Factorial of given number: 120

Working of Recursion.

In the above example, the factorial function calculates the factorial of n by making a recursive call to itself with n-1 as the argument. The if statement checks for the base case, which is when n is equal to 0 and returns 1 in that case. When the base case is not reached, the function calculates n * factorial(n-1), and this continues until the base case is reached.
recursion working for factorial
Recursion

We need to follow two simple steps to solve any recursion problem and these are:

Step 1: Divide the problem into smaller sub-problem. 
Finding the solution for a smaller sub-problem is easy compared to finding the solution for a single large problem. In recursion, we keep dividing the problem into smaller sub-problem until we find the smallest sub-problem.

Step 2: Specify the base condition to stop the recursion.
The base condition is the one that doesn't require calling the same function again and it helps in stopping the recursion. In our case, finding the factorial of 0 is the base case. 

Types of Recursion.

  • Direct Recursion
  • Indirect Recursion
  • Tail Recursion
  • Non-Tail Recursion

1. Direct Recursion.

Direct recursion is a condition in which the function calls itself directly from the inside.
//Example of direct Recursion
void fun()
{
    //some code

    fun();

}


2. Indirect Recursion.

Indirect recursion is a condition in which the first function calls the second function and the second function again calls the first function.
//Example of indirect Recursion
void fun_1()
{
    //some code
    fun_2();
}

void fun_2()
{
    //some code
    fun_1();
}

3. Tail Recursion.

A recursion function is said to be a tail recursion if the recursion call is the last thing done by the function. There is no need to keep a record of the previous state.

Example: 
//Example of Tail Recursion in C++
#include<iostream>
using namespace std;

//recursive function
int fun(int n)
{
    if(n == 0)
      return 0;
    else
      cout<<n<<" ";
    return fun(n - 1);    
}
int main(){
    //function call
    fun(3);

    return 0;
}
Output:
3 2 1

4. Non-Tail Recursion.

A recursion function is said to be non-tail recursion when the same function call is not the last thing done by the function.  After returning back there is some statement left to evaluate. 

Example:
//Non-Tail Recursion Example in C++
#include<iostream>
using namespace std;

void fun(int n)
{
  if(n == 0)
    return;

  fun(n - 1);
  cout<<n<<" ";

}

int main()
{
  //function call
  fun(3);

  return 0;
}
Output:
1 2 3


Conclusion.

  • Every recursion program can be written as iterative.
  • Every recursion program can be modeled into an iterative program but recursive programs are more elegant and require relatively fewer lines of code.
  • The recursive program requires more space in memory than iterative programs.

Python Program to Add Two Numbers.

Given two numbers num1 and num2. Write a Python program to perform the addition of given two numbers and print the output sum.

Example:

Given: num1 = 10, num2 = 20
Output: 30

Given: num1 = 5, num2 = 8
Output: 13


Example Python Code:

# take input from the user
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")

# add the two numbers
sum = float(num1) + float(num2)

# print the result
print("The sum of {0} and {1} is {2}".format(num1, num2, sum))
Output:
Enter a number: 12
Enter another number: 41
The sum of 12 and 41 is 53.0

Explanation:
This program takes two numbers as input from the user using the input() function, which returns the input as a string. The input is then converted to a float using the float() function so that the numbers can be added together. 

The result is stored in the variable sum, which is then printed out using the print() function. The format() method places the values of num1, num2, and sum into the string.

How To Create Hyperlink in HTML?

HTML links, also known as hyperlinks, allow users to navigate between web pages or different sections of a web page by clicking on text or images.


Adding Link to a Text.

The most basic way to create a link in HTML is to use the <a> (anchor) element. The <a> element has an "href" (hypertext reference) attribute that specifies the URL or web address of the page or resource that the link should point to.

Example:

<a href="https://www.example.com">Visit example.com</a>
Output:


Adding Jump Link to a section of the Page.

You can also use the <a> element to create links to specific locations within a web page. To do this, you would use the "name" attribute and the "#" symbol, followed by the name of the location you want to link to. Then, you would create the location by using the "name" attribute on the element that you want to link to.

Example:
<a href="#section1">Go to section 1</a>
...
<h2 name="section1">Section 1</h2>

Adding Link to an Image.

You can also use the <img> element to link an image. In this case, the <img> element should be nested within the <a> element and the <img> element should have an "src" attribute that specifies the URL of the image file.

Example:
<a href="https://www.example.com">
    <img src="example.jpg" alt="Example">
</a>

It's important to note that the <a> element should always have a closing tag </a> and the value of the "href" attribute must always be enclosed in quotation marks.

Heap Sort Algorithm in C++

In this post, we are going to understand Heap sort which is similar to the selection sort algorithm for sorting data.


Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure to sort an array. A binary heap is a complete binary tree that satisfies the "heap property," which states that the value of each node is greater than or equal to the values of its children (for a max-heap) or less than or equal to the values of its children (for a min-heap).


The basic steps of the heap sort algorithm in C++:

Step 1. Build a max-heap from the input array.

void build_max_heap(int arr[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
}

Step 2: Swap the root (maximum value) of the heap with the last element of the array. This moves the maximum value to the end of the array. Then, call the heapify function on the remaining elements, except the last one, to maintain the heap property.

void heap_sort(int arr[], int n) {
    build_max_heap(arr, n);

    for (int i = n-1; i >= 0; i--) {
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
}

Step 3: The heapify function is used to maintain the heap property. It compares the value of the node with its children and if the value of the node is less than the value of its children, it swaps the values of the node with the largest value among its children.

void heapify(int arr[], int n, int i) {
    int largest = i;
    int l = 2*i + 1;
    int r = 2*i + 2;

    if (l < n && arr[l] > arr[largest])
        largest = l;

    if (r < n && arr[r] > arr[largest])
        largest = r;

    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}

Complete C++ Program for Heap Sort.
//C++ Example for Heap Sort Algorithm
#include<iostream>
using namespace std;

void heapify(int arr[], int n, int i) {
    int largest = i;
    int l = 2*i + 1;
    int r = 2*i + 2;

    if (l < n && arr[l] > arr[largest])
        largest = l;

    if (r < n && arr[r] > arr[largest])
        largest = r;

    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}
//function to build max heap
void build_max_heap(int arr[], int n) {
    for (int i = n / 2 - 1; i >= 0; i--)
        heapify(arr, n, i);
}
//heap sort function
void heap_sort(int arr[], int n) {
    build_max_heap(arr, n);

    for (int i = n-1; i >= 0; i--) {
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
}

int main()
{
    int arr[] = {3, 8, 1, 4, 2, 11};
    int n = sizeof(arr)/sizeof(arr[0]);

    heap_sort(arr, n);

    for(int i = 0; i < n; i++)
       cout<<arr[i]<<" ";

    return 0;   
}
Output:
1 2 3 4 8 11
  • Time Complexity: O(n log n)
  • Space Complexity: O(1)
Heap sort is better than bubble sort and selection sort but not better than insertion sort.

Colors in HTML

Colors play an essential role in web design, and HTML provides several ways to specify colors for different elements on a web page. In this article, we will discuss the different ways to specify colors in HTML, and some best practices to keep in mind when using colors in web design.


There are three main ways to specify colors in HTML: 

  • Using Color names.
  • Using Hex codes.
  • Using RGB values.


Using Color names.

Color names are the simplest way to specify colors in HTML. There are 140 predefined color names in HTML such as "red", "green", "blue", etc. To use a color name, specify the color name as the value of the "color" property. 


For example, to set the text color of a paragraph to red, you would use the following code:

<p style="color: red">This paragraph text is red</p>
Output:
Color name in HTML

Using Hex codes.

Hex codes are another way to specify colors in HTML. A hex code is a six-digit code that represents a color in the RGB color model. To use a hex code, prefix it with a "#" symbol and specify it as the value of the "color" property. 

For example, to set the text color of a paragraph to dark blue, you would use the following code:
<h2 style="color: #0ebd4b">This is a sub-heading</h2>
<p style="color: #00008b">This paragraph text is dark blue</p>
Output:
Hex Code in HTML

Using RGB Values.

RGB stands for Red, Green, and Blue and is a way to represent colors in HTML. The RGB color model is an additive color model in which red, green and blue light are added together in various ways to reproduce a broad array of colors.

In HTML, RGB colors can be specified using the "rgb()" function in a CSS "color" or "background-color" property. The function takes three values, one for each of the color's red, green, and blue components, and must be in the range of 0-255.

Example:
<p style="color: rgb(255, 0, 0);">This text is red.</p>
<div style="background-color: rgb(0, 255, 0);">This background is green.</div>
Output:
RGB Color in HTML

You can also use a variation called RGBA which stands for Red, Green, Blue, and Alpha, which is a value between 0 and 1 representing the opacity of the color.

Example:
<p style="color: rgba(255, 0, 0)">This text is red with 100% opacity</p>
<p style="color: rgba(255, 0, 0, 0.5)">This text is red with 50% opacity</p>
Output:
RGBA color in HTML


C++ Program to Find Simple Interest

Simple interest is calculated by multiplying the principal amount, the interest rate, and the time period. The formula for simple interest is:

I = (P * R * T) / 100

Where I is the interest, P is the principal amount, R is the interest rate, and T is the time period.


Here is an example C++ program that calculates the simple interest:

//C++ Example Program to find Simple Interest
#include <iostream>
using namespace std;

int main() {
    float P, R, T, I;

    // Input the principal amount, interest rate, and time period
    cout << "Enter the principal amount: ";
    cin >> P;
    cout << "Enter the interest rate: ";
    cin >> R;
    cout << "Enter the time period: ";
    cin >> T;

    // Calculate the simple interest
    I = (P * R * T) / 100;

    // Display the result
    cout << "Simple Interest = " << I;

    return 0;
}
Output:
Enter the principal amount: 10000
Enter the interest rate: 10
Enter the time period: 5
Simple Interest = 5000

In this example, the user is prompted to input the principal amount, interest rate, and time period. The program then calculates the simple interest using the formula and displays the result.

Also read:

Comments in HTML. (Shortcut Key)

Comments play an important role in coding, they help developers understand, organize, and maintain their codebase. In HTML, comments serve as annotations within the code, offering, insights, explanations, and reminders without affecting the displayed content. Let's understand their types, usage, and essential shortcuts. 


Why Use Comments in HTML?

In HTML, comments are used to add notes or explanations to the source code of a web page. They serve multiple purposes:

  • They help document the code, providing explanations for specific sections or lines.
  • They improve code readability, assisting developers in comprehending complex or intricate structures.
  • Comments can be used to identify or isolate issues within the code during troubleshooting or debugging processes.
  • They facilitate collaboration among developers by conveying intentions, strategies, or notes within the code.

Types of Comments in HTML.

Comments are not displayed in the browser and are ignored when the page is rendered. HTML supports two types of comments:

1. Single-line Comments: Denoted by <!-- -->, single-line comments are used for brief annotations on a single line. 

Example of Single-line Comment:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Comment Example</title>
  </head>
  <body>
    <!--This is a single line comment in HTML-->
    <h2>This is a Heading.</h2>
    <h3>Welcome to AlgoLesson</h3>
  </body>
</html>

Output:


2. Multi-line Comments: Enclosed between 
<!-- and closing -->, multi-line comments span across multiple lines and are useful for detailed explanations or larger annotations. Comments can be added anywhere within the HTML code and can span multiple lines.

Example of Multi-line Comment:
<!DOCTYPE html>
<html>
  <head>
    <title>HTML Comment Example</title>
  </head>
  <body>
    <!--This is a multi-line comment in HTML
        This will not be displayed on the browser screen-->
    <h2>This is a Heading.</h2>
    <h3>Welcome to AlgoLesson</h3>
  </body>
</html>

Inline Comment in HTML

In HTML, comments can be also used inside the content or in the middle of the code. 

Example: 
<p>This is a simple paragraph in HTML.</p>
<p>This an example of <!--comment inside--> HTML content.</p>
Output:
Inline Comment in HTML

HTML Comment Shortcuts.

While various text editors and IDEs offer shortcuts to insert comments easily, some widely used keyboard shortcuts for adding comments in HTML are:
  • Visual Studio Code: Ctrl + / (Windows/Linux) or Cmd + / (Mac) to toggle comments for selected lines.
  • Sublime Text: Ctrl + / (Windows/Linux) or Cmd + / (Mac) to toggle comments for selected lines.
  • Notepad++: Ctrl + Shift + Q to add or remove comments for selected lines.

I hope that now you understand how to use Comments in HTML and why they are so important for developers. It helps us create a clean, maintainable, and well-documented codebase.

DON'T MISS

Nature, Health, Fitness
© all rights reserved
made with by AlgoLesson