Singly Linked List copy constructor value order?
I want to add the nodes of MyString in the same order as in the
original class so that I can print "ch" field in the same order for
both classes. I was thinking of navigating until the end of list of
original class with a trailing pointer and inserting nodes backwards
so that I can print them in the same positions. But since this is a
singly list I can't get back to previous node. Another option I
thought is to traverse the list a second time and relink all nodes but
I don't like this idea because of the extra overhead of another loop.
Any other suggestions?
This is the input and output of the program below:
Input
Enter Char:
a
Enter Char:
b
Enter Char:
c
Output
Printing Values:
c
b
a
Copied Printing Values:
a
b
c
I want both to look like this:
c
b
a
#include <iostream>
#include <string>
using namespace std;
struct Node
{
char ch;
Node *next;
};
class MyString
{
private:
Node *mystr;
public:
MyString();
MyString(MyString& m);
Node* CreateNode(char);
void Insert(Node* nd);
void AddNode(char);
void readStr();
void printStr();
void deleteStr();
};
MyString::MyString()
{
mystr = NULL;
}
MyString::MyString(MyString& m)
{
Node* ptr;
Node* tptr;
mystr=NULL;
ptr= m.mystr;
while (ptr!=NULL)
{
Node *newnode;
newnode=CreateNode(ptr->ch);
Insert(newnode);
tptr=ptr;
ptr=ptr->next;
}
}
void MyString::Insert(Node* nd)
{
if (mystr!=NULL)
{
nd->next = mystr;
}
mystr=nd;
}
Node* MyString:: CreateNode(char c)
{
Node* newnode;
newnode = new Node;
newnode->ch= c;
newnode->next = NULL;
return newnode;
}
void MyString::AddNode(char c)
{
Node *newnode;
newnode = new Node; // alocates space
newnode->ch = c;
newnode->next = mystr;
mystr = newnode;
}
void MyString:: readStr()
{
char c;
cout << "Enter Char:" << endl;
cin >> c;
AddNode(c);
}
void MyString::printStr()
{
Node *ptr;
ptr = mystr;
cout << "Printing Values: " << endl;
while (ptr!=NULL)
{
cout << ptr->ch << endl;
ptr = ptr->next;
}
}
int main()
{
MyString m1 = MyString();
m1.readStr(); // read 'a'
m1.readStr(); // read 'b'
m1.readStr(); // read 'c'
m1.printStr();
MyString m2 = MyString(m1);
m2.printStr();
return 0;
}
Thanks Rod