Find the Nth Node from the End of a Linked List Using Bash

This Bash script demonstrates how to find the nth node from the end of a linked list, using an array to simulate the linked list. The linked list is represented by an array where each index represents a node. The task is to find the node that is nth from the last node.

Bash Script Code


#!/bin/bash

# Function to find the nth node from the end of a list
find_nth_from_end() {
    local -a list=("$@") # The list is passed as an array of elements
    local length=${#list[@]}
    local nth=$1
    local index=$((length - nth))

    if [[ index -lt 0 || index -ge length ]]; then
        echo "Invalid n: $nth. The list has only $length nodes."
        return 1
    fi

    echo "The ${nth}th node from the end is: ${list[index]}"
}

# Example list (array)
list=(10 20 30 40 50 60 70 80 90 100)

# Call the function with the list and nth value
find_nth_from_end 3 "${list[@]}"

Explanation of the Code

The script includes a function find_nth_from_end that calculates the nth node from the end of a simulated linked list:

  1. Array Initialization: The function accepts a list passed as an array and an integer n, indicating the nth position from the end.
  2. Calculation: It calculates the index of the desired element by subtracting n from the length of the array. This provides the position of the nth node from the end.
  3. Validation and Output: The script checks if the calculated index is valid. If so, it prints the value of the nth node from the end. If not, it outputs an error message.

Output and Use Case

For the example list and an nth value of 3, the script will output “The 3rd node from the end is: 80”, correctly identifying the third last element in the array.

 

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 :)