Remove Duplicate Elements from a Linked List Using Bash

This Bash script demonstrates how to remove duplicate elements from a linked list, which is represented as an array. Each index in the array represents a node in the linked list, and the script will remove any duplicate nodes from it.

Bash Script Code


#!/bin/bash

# Function to remove duplicates from a list
remove_duplicates() {
    local -a list=("$@")
    local -a unique=()
    local -A seen=()  # associative array to track seen elements

    for item in "${list[@]}"; do
        if [[ -z "${seen[$item]}" ]]; then
            unique+=( "$item" )
            seen["$item"]=1
        fi
    done

    echo "List after removing duplicates: ${unique[@]}"
}

# Example list with duplicates
list=(1 2 3 4 5 3 2 6 7 8 9 7)

# Call the function with the list
remove_duplicates "${list[@]}"

Explanation of the Code

The script includes a function remove_duplicates that processes an array (simulating a linked list) and removes any duplicate elements:

  1. Array Initialization: The function takes a list of values and initializes an associative array seen to track which elements have appeared.
  2. Duplicate Removal: It iterates through each element in the list. If the element has not been encountered before (checked using the seen associative array), it is added to the unique array.
  3. Output: After processing all elements, the function outputs the list with duplicates removed.

Output and Use Case

For the given example list, the function will output “List after removing duplicates: 1 2 3 4 5 6 7 8 9”, successfully identifying and removing duplicated elements.

 

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