hi!
i have written a code of linked list using character array to add and display data, it can add data but not display.
can anyone help??
thanks.

#include<iostream>
using namespace std;
class node

private:
    char data[30];
    node* next;
public:
    char showdata()
    {
        return data[30];
    }
    void setdata(char c[40])
    {
        strcpy(data,c);
    }
    node* shownext()
    {
        return next;
    }
    void setnext(node* n)
    {
        next=n;
    }
};
class list
{
private:
    node* hn;
    node* cn;
    node* lcn;
    int size;
public:
    list()
    {
        size=0;
        hn=new node();
        hn->setnext(NULL);
        cn=NULL;
        lcn=NULL;
    }
    void add()
    {
        char c[30];
        node* newnode= new node();
        cout<<"enter name : ";
        cin>>c;
        newnode->setdata(c);
        if(cn!=NULL)
        {
            newnode->setnext(cn->shownext());
            cn->setnext(newnode);
            lcn=cn;
            cn=newnode;
        }
        else
        {
            newnode->setnext(NULL);
            hn->setnext(newnode);
            lcn=hn;
        }
    }
    void display()
    {
        cn=hn->shownext();
        while(cn!=NULL)
        {
            cout<<cn->showdata();
            cn=cn->shownext();
        }
    }

};
int main()
{
    int n;
    cout<<"enter num of items you want to add in list: ";
    cin>>n;
    list l;
    for(int i=0;i<n;i++)
    {
        l.add();
    }
    for(int i=0;i<n;i++)
    {
        l.display();
    }
    return 0;
}

Your code is a little complex for me.
The Node is responsible for holding data not adding, deleting or displaying.
Each Node in your code now has its own funtions and i don't think its a good way.
Make a Display funtion in List to display all Nodes, pretty simple
Let the the List class responsible to hold the Nodes, add Nodes, deleting Nodes and Display them. Thats how a container works.

I'm still a newbie, sorry for any mistake.

Aside from the design issues, the showdata routine only returns 1 char. You will probably find more success making the return type char* and passing the character array as the return data:

char* showdata()
{
    return data;
}

Edited 2 Years Ago by tinstaafl

This article has been dead for over six months. Start a new discussion instead.