Check if a Linked List is a Palindrome Using Bash

This Bash script demonstrates a simple approach to determine if a linked list (represented as an array in Bash) is a palindrome. A palindrome is a sequence that reads the same forward and backward.

Bash Code


#!/bin/bash

# Function to check if the list is a palindrome
is_palindrome() {
    local -a list=("$@") # Receive list elements as an array
    local i=0
    local j=$((${#list[@]} - 1))

    while [[ $i -lt $j ]]; do
        if [[ "${list[$i]}" != "${list[$j]}" ]]; then
            echo "The list is not a palindrome."
            return
        fi
        ((i++))
        ((j--))
    done

    echo "The list is a palindrome."
}

# Example list (Should be input as separate arguments)
is_palindrome 1 2 3 2 1

Explanation of the Code

The script defines a function is_palindrome which checks whether a given list is a palindrome. It works as follows:

  1. Array Initialization: The function takes a list of values from the command line and initializes a Bash array.
  2. Checking Palindrome: Two indices, i (starting from the beginning) and j (starting from the end), are used to compare elements of the array. If any pair of elements at these indices are not equal, the list is immediately declared not a palindrome.
  3. Loop and Compare: The indices i and j are incremented and decremented, respectively, until they meet in the middle, ensuring all elements are checked.

Output and Use Case

When running the function with the arguments 1 2 3 2 1, the script outputs that the list is a palindrome because the sequence reads the same forwards and backwards. Adjusting the input can be used to test other sequences.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)