All about C plus plus algorithms!

Monday 17 July 2017

Linked String in C++ || PART 2 || C++ Class

As we have already discussed in the previous post about linked lists and how they work. Please view Linked String in C++ || PART 1 || C++ Class to see that post.


I have written the code for Singly linked list for characters. To assist creating nodes, I have made a function called CreateNode( ) inside the private of this class. This function creates a new node and returns the address of it. I have not made it public because the public users need not to make new nodes.

struct Node
{
char c;
Node* next;
};

class LinkedString
{
private:


Node* head, *tail;
int size;

Node* CreateNode(char d)
{
Node* temp = new Node;
temp->next = nullptr;
temp->c = d;
return temp;  //address of the created node
}

}

In the public, I have first made constructors.

LinkedString()   //default constructor
{
head = tail = nullptr;
size = 0;

}

LinkedString(const string & str)   //takes string as input and stores in the linked list
{
char c;
int n = str.size();

int i = 0;
while ( i < n)
{
c = str.at(i);

addCharAtEnd(c);

i++;
}
}

LinkedString(const LinkedString & obj)   //copy constructor
{

LinkedString lnk;

Node* holder = obj.head;
// size = 0;
if (holder != nullptr)
{
while (holder->next != nullptr)
{

lnk.addCharAtEnd(holder->c);  //the helping function made in private
holder = holder->next;
}

head = lnk.head;
tail = lnk.tail;
size = lnk.size;
}

}

As you can see I have used a function addCharAtEnd() in the copy constructor that inserts new node at the end of the list and makes the tail point to it. Its code will go into the private section of the class.


void  addCharAtEnd(char ch)
{
if (size == 0)
{
size++;
head = tail = CreateNode(ch);

}
else
{
tail->next = CreateNode(ch);
tail = tail->next;

size++;
}
}

Now I can't go explaining all the functions that I have made; some private, some public. So I will share the code only.

Here is the link to the drive folder containing the Header file which has the code for the class and a sample main file the run tests on those functions.

Source files for Linked List



Thank you for reading! ^^ And if you have any questions or confusions regarding the code, comment below. :)

Share:

0 comments:

Post a Comment

Popular Posts

Blog Archive

Copyright by progrithms.blogspot.com. All Rights Reserved.. Powered by Blogger.

Copyright © Programs and Algorithms | Powered by Blogger

Design by ThemePacific | Blogger Theme by NewBloggerThemes.com