Software & Finance





Visual C++ - Singly Linked List





I have given here Visual C++ sample code for singly linked list, filling elements and traversal in forward direction. 

 

Singly Linked List, Doubly Linked List, Singly Linked Circular List and Doubly Linked Circular List are an important data structure used in C++ applications.

Related Links:



Source Code


// Program for singly linked list

 

#include <iostream>

#include <string>

 

struct SLinkList

{

    std::string data;

    SLinkList *next;

 

    SLinkList() : data(""), next(NULL) { }

    SLinkList(const char *value) : data(value), next(NULL) { }

 

    SLinkList* InsertNext(const char *data)

    {

        SLinkList *node = new SLinkList(data);

        if(this->next == NULL)

        {

            // Easy to handle

            node->next = NULL; // already set in constructor

            this->next = node;

        }

        else

        {

            // Insert in the middle

            SLinkList *temp = this->next;

            node->next = temp;

            this->next = node;

        }

        return node;

    }

 

    bool DeleteNext()

    {

        if(this->next == NULL)

            return false;

        SLinkList *pNode = this->next;

        this->next = this->next->next;  // can be NULL here

        delete pNode;

    }

 

    void Traverse(SLinkList *node = NULL)

    {

        if(node == NULL)

            node = this;

        std::cout << "\n\nTraversing in Forward Direction\n\n";

        while(node != NULL)

        {

            std::cout << node->data;

            std::cout << "\n";

            node = node->next;

        }

    }

};

 

int main()

{

    SLinkList *node1 = new SLinkList("ONE");

    SLinkList *node2 = node1->InsertNext("TWO");

    SLinkList *node3 = node2->InsertNext("THREE");

    SLinkList *node4 = node3->InsertNext("FOUR");

    SLinkList *node5 = node4->InsertNext("FIVE");

 

    node1->Traverse();

    node3->DeleteNext(); // delete the node "FOUR"

    node2->Traverse();

   

    std::cout << "\n";  

    return 0;

}

Output


 

Traversing in Forward Direction

ONE
TWO
THREE
FOUR
FIVE

 

Traversing in Forward Direction

TWO
THREE
FIVE