Remove Duplicate Elements from a Linked List Using Bash

 

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *