Check if a Linked List is a Palindrome Using Bash

 

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.

 

Leave a Reply

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