Find Intersection of Two Linked Lists Using Bash

This Bash script simulates the operation of finding the intersection point of two linked lists. In our simulation, linked lists are represented as arrays, and the intersection is determined by the index at which the two arrays first share a common value.

Bash Script Code


#!/bin/bash

# Function to find intersection of two lists
find_intersection() {
    local -a list1=("${!1}") # Receive first list
    local -a list2=("${!2}") # Receive second list

    for i in "${!list1[@]}"; do
        for j in "${!list2[@]}"; do
            if [[ "${list1[$i]}" -eq "${list2[$j]}" ]]; then
                echo "Intersection found at list1 index $i and list2 index $j, value: ${list1[$i]}"
                return
            fi
        done
    done

    echo "No intersection found."
}

# Example lists (arrays)
list1=(1 2 3 4 5)
list2=(9 8 7 6 5)

# Call the function with array names
find_intersection list1[@] list2[@]

Explanation of the Code

The script defines a function find_intersection to identify the intersection point of two lists:

  1. Array Initialization: The function accepts two Bash arrays as inputs, passed by reference.
  2. Nested Loop Structure: Two nested loops iterate over each element of the first list and each element of the second list.
  3. Comparison and Output: Elements from both lists are compared. If a common element is found, the function prints the index and value of the intersection and exits. If no common elements are found throughout the loops, a message indicating no intersection is printed.

Output and Use Case

For the given example lists, the function will find that the value ‘5’ is common to both, located at index 4 in list1 and index 4 in list2. The script will output this intersection detail.

 

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