An efficient method to eliminate an element from a linked list

In a TED talk by Linus Torvalds, he demonstrated both "poor" and "good" programming practices using an example of removing an item from a linked list.

First, the poor taste example:

https://i.sstatic.net/pgZTo.png

Now, the good taste example:

https://i.sstatic.net/6RUWe.png

The key difference lies in the last if statement in the bad taste example.

As someone who is not well-versed in C/C++ development, I find myself naturally gravitating towards the "bad" taste approach.

My question is: Is it possible to write a more elegant solution without relying on if statements for handling special cases in languages like Java or JavaScript that do not utilize C-style pointers?

Answer №1

Concerning your inquiry:

Can a "smart" solution be devised without resorting to if statements for specific cases in a programming language that does not support C-style pointers?

The response:

There are virtually limitless possibilities when it comes to writing code.

Answer №2

I have expanded the code snippets into a complete .c file to provide a better understanding within the context:

struct node {
    int data;
    struct node* next;
}

typedef struct node nodde_t;

node_t* head;

/*bad code*/
void remove_list_entry_bad(node_t* entry){
    node_t* prev = NULL;
    node_t* walk = head;

    while(walk != entry){
        prev = walk;
        walk = walk->next;
    }

    if(!prev)
        head = entry->next;
    else
        prev->next = entry->next;
}

/*good code*/
void remove_list_entry_good(node_t* entry){
    
    node_t** indirect = &head;

    while ((*indirect) != entry)
        indirect = &(*indirect)->next;

    *indirect = entry->next;
}

int main(){

    node_t n1, n2, n3;
    
    n1.data = 45;
    n2.data = 8;
    n3.data = 32;

    head = &n1; 
    n1.next = &n2;
    n2.next = &n3;
    n3.next = NULL;
    
    remove_list_entry_good(&n2); /* instead : n1.next = &n3; */

    return 0;

}

To keep things simple, I chose Integers as the data type for this implementation. The typedef is used to simplify writing node_t instead of struct node in the code. In C, you typically need to include the struct keyword whenever using a custom data type like node.

If pointers are unfamiliar, think of the Java version of this code with references replacing pointers:

package linked;
class Node {
    int data;
    Node next;
}
public class Test {
    Node head;

    /* bad code */
    void remove_list_entry_bad(Node entry) {
        Node prev = null;
        Node walk = head;

        while (walk != entry) {
            prev = walk;
            walk = walk.next;
        }

        if (prev == null)
            head = entry.next;
        else
            prev.next = entry.next;
    }

    /* good code */
    void remove_list_entry_good(Node entry) {
        Node indirect = head;

        while (indirect.next != entry)
            indirect = indirect.next;

        indirect.next = entry.next;
    }

    public static void main(String[] args) {

        Node n1, n2, n3;
        
        n1 = new Node();
        n2 = new Node();
        n3 = new Node();

        n1.data = 45;
        n2.data = 8;
        n3.data = 32;

        Test list = new Test();
        list.head = new Node();
        list.head.next = n1;
        n1.next = n2;
        n2.next = n3;
        n3.next = null;


        list.remove_list_entry_good(n1);

        Node walk = list.head.next;
        while (walk != null) {
            System.out.println("" + walk.data);
            walk = walk.next;
        }

    }
}

The Node class utilizes a recursive definition, similar to methods that call themselves repeatedly. Placing the Node class inside the MyList class signifies it as a private class.

Edit I discovered something intriguing in C where the type of indirect must be node_t** with double stars. Though the exact implications are unclear, it functions correctly.

Edit I stumbled upon a simple and effective solution online!

void remove_list_entry_good(Node entry) {
    Node temp = entry.next; 
    entry.value = temp.value; 
    entry.next = temp.next; 
    temp = null; 
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for utilizing a function to calculate the value of a specific member within a structure in C by utilizing the values of other members?

I coded a struct in C that includes three integer members. My goal is to calculate the value of member C by adding the values of A and B within a function in the code below. #include <stdio.h> typedef struct nums { int a; int b; int c; } numb ...

Interested in creating a personalized rotating display like this one, but not sure what it's called?

https://i.sstatic.net/geKaA.png I'm in the process of building a website focused on movie recommendations, and I've developed a REST API using Python deployed on Heroku. To fetch the data, I'm utilizing Ajax. $.ajax({ url: ...

Utilizing Promise and setTimeout in a generator function to develop an asynchronous generator: A comprehensive guide

I am currently working on creating a generator function that produces an async generator. This Generator will yield a deferred value at each time, using promises. The values and their respective delays (in milliseconds) are sourced from two separate arrays ...

Is there a way to implement a react component into an HTML file?

I initially created a web page using pure JS, CSS, and Django. Feeling quite ineffective, I decided to try using React JS instead. However, upon making a simple React component, I encountered a problem - I wasn't sure how to incorporate this component ...

What is the purpose of using @ViewChild to access a component's function from another component?

During a discussion with my tutor, I learned that in Angular we can utilize functions defined in any service by simply importing the service. However, unlike services, components cannot be directly imported into other components. To access a function from ...

Develop an enhancement for the Date object in Angular 2 using Typescript

Using the built-in Date type, I can easily call date.getDate(), date.getMonth()...etc. However, I am looking for a way to create a custom function like date.myCustomFunctionToGetMonthInString(date) that would return the month in a string format such as &a ...

Divide the string by using a smaller part of it

Just starting out with android and I have a specific scenario to address. Below is the string that I am working with: file=android.txt&data="sampleExample" How do I go about extracting the substrings android.txt and sampleExample? NOTE: I ...

Steps to establish a connection to a MySQL database using Eclipse

I am currently running an application in Eclipse Kepler with a MySQL database on AWS RDS. I have imported the mysql-connector-java-gpl-5.1.31-.msi and aws-java-sdk-1.8.5.jar files for this setup. My goal is to perform various operations like creating new ...

Show the div only if a different ID is activated

I seem to be having trouble targeting only one div element. Specifically, when I click on "impressum," only the impressum content is displayed within the <div class="ContentBox">. However, when I click on "AboutMe," both the AboutMe and impressum co ...

The StrongLoop ng-lb command encounters issues when utilizing the local-storage-connector

Hello Strongloop community, I have been experimenting with the local-storage data store example provided by loopback. It's working well and I can successfully create and retrieve files from the local file system (used as a data source) using the REST ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...

Receiving a reply from the axios function

Whenever I try to call the lookUpItem function from ItemSearch.vue, I always get an undefined response. Code snippet from ItemSearch.vue: <script setup lang="ts"> import { lookUpItem } from '../systemApi' async fu ...

Receiving HTML from NodeJs instead of JSON

I am currently working on a project that involves developing an app and landing pages. While we are using NodeJs with Axios and VueJs for the app part, the landing pages are built using simple jQuery. I need to make API calls for the landing pages, but I a ...

Can you specify the third argument sent to the listener?

Recently I delved into exploring the capabilities of the d3 framework. One thing that caught my attention was the presence of a third parameter in the event listener for v3. Despite always being 0, I couldn't find any explanation on its intended purpo ...

Having trouble retrieving json data from PHP page using jQuery $.ajax

Having trouble accessing this JSON data in JavaScript, as when I try to alert it the result comes back as undefined Below is the jQuery code snippet: $.ajax({ type: "POST", url: "frmMktHelpGridd.php", data: { labNo: secondElement ...

Issue with Subquery Incorrectly Filtering in Spring Boot SQL Query

This is the repository I have for searching subjects that are not announced: import com.tetradunity.server.entities.SubjectEntity; import com.tetradunity.server.models.SubjectFilter; import com.tetradunity.server.projections.AnnounceSubjectProjection; impo ...

Encountering difficulty in locating the specified activity class while attempting to initiate a Service

I encountered an issue while attempting to retrieve values of a class from another class. Despite exploring various solutions on StackOverflow, I am still unable to resolve the issue. I suspect that the problem lies in the fact that my class extends from ...

What is the best way to search for all results in MongoDB that have x appearing in any property?

Is it possible to search for all pictures in the mongoose framework with node and express that contain a specific parameter, regardless of which property holds that parameter? For example: If I enter "John Snow" in the search bar, I want to see all pictur ...

Best Practices for Making Remote Requests in Ruby on Rails

Currently, I am creating a Single Page Application using Ruby on Rails for the first time. Although I am still learning, I have set up a side menu with links and a container on the right part of the page to display partial pages. An example of one of my me ...

Tips on getting the bot to react to a single "event" mentioned in the sentence, without multiple occurrences

Things are a bit complicated, but here's an example to illustrate: I've set up this event: client.on('message', async message => { if (message.content.toLowerCase().includes("megumin")) { message.channel.send("W ...