Adding Two Numbers Represented by Linked Lists in Bash

This Bash program simulates adding two numbers where each number is represented by a linked list. Each node in the list represents a single digit. The digits are stored in arrays, with the least significant digit at the start of the array (representing the head of the list).

Program Code


#!/bin/bash

# Function to add two numbers represented as reversed arrays
add_linked_lists() {
    local -n list1=$1
    local -n list2=$2
    local carry=0
    local -a result=()

    local max_length=$(( ${#list1[@]} > ${#list2[@]} ? ${#list1[@]} : ${#list2[@]} ))

    for (( i=0; i<$max_length || carry; i++ )); do
        local sum=$(( ${list1[i]:-0} + ${list2[i]:-0} + carry ))
        result[i]=$(( sum % 10 ))
        carry=$(( sum / 10 ))
    done

    echo ${result[@]}
}

# Example usage:
# Represent numbers 243 (3->4->2) and 564 (4->6->5) by arrays
list1=(3 4 2)
list2=(4 6 5)

# Add the numbers
result=$(add_linked_lists list1 list2)
echo "Result: $result"

Explanation of the Code

The Bash script defines a function add_linked_lists that takes two arrays (list1 and list2) as input. Each array contains the digits of a number in reverse order (least significant digit first). The function calculates the sum of these two numbers assuming each digit is a node in a linked list.

The max_length determines the length of the longer array to iterate over all digits. The loop sums corresponding digits of both numbers and handles the carry for digits exceeding 9. If there is a carry left after the last digit, it is added to the result. The function returns the sum as an array with digits in reverse order, representing the resulting linked list.

Use Case and Output

When adding 243 and 564 represented as linked lists, the script outputs the digits of the result (807) as a linked list in reverse order (7 0 8), which corresponds to the number 807.

 

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