How to resolve the algorithm Doubly-linked list/Element insertion step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Doubly-linked list/Element insertion step by step in the D programming language

Table of Contents

Problem Statement

This is much like inserting into a Singly-Linked List, but with added assignments so that the backwards-pointing links remain correct.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Doubly-linked list/Element insertion step by step in the D programming language

Source code in the d programming language

import std.stdio;

struct Node(T) {
    T data;
    typeof(this)* prev, next;
}

/// If prev is null, prev gets to point to a new node.
void insertAfter(T)(ref Node!T* prev, T item) pure nothrow {
    if (prev) {
        auto newNode = new Node!T(item, prev, prev.next);
        prev.next = newNode;
        if (newNode.next)
            newNode.next.prev = newNode;
    } else
        prev = new Node!T(item);
}

void show(T)(Node!T* list) {
    while (list) {
        write(list.data, " ");
        list = list.next;
    }
    writeln;
}

void main() {
    Node!(string)* list;
    insertAfter(list, "A");
    list.show;
    insertAfter(list, "B");
    list.show;
    insertAfter(list, "C");
    list.show;
}


  

You may also check:How to resolve the algorithm XML/Output step by step in the Oz programming language
You may also check:How to resolve the algorithm Mandelbrot set step by step in the Scheme programming language
You may also check:How to resolve the algorithm Averages/Arithmetic mean step by step in the Ursa programming language
You may also check:How to resolve the algorithm Factorial step by step in the Modula-2 programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Phix programming language