Software & Finance





Turbo C++ - Singly Linked List





I have given here Turbo 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


#include <iostream.h>

#include <string.h>

 

struct SLinkList

{

    int data;

    SLinkList *next;

 

    SLinkList();

    SLinkList(int value);

 

    SLinkList* InsertNext(int value);

    int DeleteNext();

 

    void Traverse(SLinkList *node = NULL);

};

 

SLinkList::SLinkList() : data(0), next(NULL)

{

}

 

SLinkList::SLinkList(int value) : data(value), next(NULL)

{

}

 

 

SLinkList* SLinkList::InsertNext(int value)

{

    SLinkList *node = new SLinkList(value);

    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;

}

 

int SLinkList::DeleteNext()

{

    if(this->next == NULL)

       return 0;

 

    SLinkList *pNode = this->next;

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

    delete pNode;

    return 1;

}

 

void SLinkList::Traverse(SLinkList *node)

{

    if(node == NULL)

       node = this;

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

 

    while(node != NULL)

    {

       cout << node->data;

       cout << "\n";

       node = node->next;

    }

}

 

 

int main()

{

    SLinkList *node1 = new SLinkList(1);

    SLinkList *node2 = node1->InsertNext(2);

    SLinkList *node3 = node2->InsertNext(3);

    SLinkList *node4 = node3->InsertNext(4);

    SLinkList *node5 = node4->InsertNext(5);

 

    node1->Traverse();

 

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

 

    node2->Traverse();

 

    cout << "\n";

    return 0;

}

 

Output


 

Traversing in Forward Direction

1
2
3
4
5

 

Traversing in Forward Direction

2
3
4