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:
- Array Initialization: The function accepts a list passed as an array and an integer n, indicating the nth position from the end.
- 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.
- 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.