Solved

Classes and linked lists? Help!

Posted on 1998-08-11
14
269 Views
Last Modified: 2013-12-14
Hi out there. I wonder if you can help me. I have just written a program in C++ for Windows that uses linked lists to create, modify, delete and display personal details.

Just for fun, but now i am wondering why, i am attempting to convert the program into classes. I am finding this excruciatingly hard as i have never used classes before. All the appropriate books don't seem to be using the struct command, and they don't show how to input details in a classes environment, like name, date of birth, etc.
I have searched the web for relevant examples as well, but i can't find any to match mine.

If anyone would like to attempt to convert my program (which follows below) into classes but at the same time trying to keep it simple, i would be very grateful, as i have tryed, but more often than not, ended up very angry and red!!!

As for changing the struct to a class, if it is possible, that would be good because i have used them for a bit now.

I am fairly interested in using classes more often. However, getting started with this is a nightmare.

If anyone does decide to have a go, comments would be appreciated as to why everybody raves about OOP, and why it would be beneficial for an amateur programmer, like myself, to use them.

------------------------------------------------------------

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<iostream.h>
#include<string.h>

struct dif
{
      char name[30];
      char dob[30];
      char tel[30];
      struct dif *ptrnext;
};

struct dif *ptrfirst, *ptrthis, *ptrnew;

char temp[30];

void main(void)
{
      int command;

      void perform(int &);
      void wait(void);

      ptrfirst=(struct dif*)NULL;

      do
      {
            clrscr();
            cout<<"1:create/insert (a new structure into the linked list)\n";
            cout<<"2:modify (an existing structure)\n";
            cout<<"3:delete (an existing structure)\n";
            cout<<"4:display (a linked list)\n";
            cout<<"0:exit (from program)\n";
            cout<<"enter command:> ";
            cin>>command;
            perform(command);
      }while(command!=0);
}

void perform(int &option)
{
      void cresert(void);
      void modify(void);
      void del(void);
      void display(void);

      switch(option)
      {
            case 1:cresert();break;
            case 2:modify();break;
            case 3:del();break;
            case 4:display();break;
            case 0:clrscr();cout<<"end of session";break;
            default:clrscr();cout<<"error. invalid command. try again!";getchar();
            break;
      }
}

void wait(void)
{
      char ch;
      cout<<"\n\n\npress <return> to go back to menu";
      scanf("%c",&ch);
      flushall();
}

void cresert(void)
{
      clrscr();
      cout<<"1: create/insert\n";

      ptrnew=(struct dif*) malloc(sizeof(struct dif));

      if(ptrfirst==(struct dif*)NULL)
            ptrfirst=ptrthis=ptrnew;
      else
      {
            ptrthis=ptrfirst;
            while(ptrthis->ptrnext!=(struct dif*)NULL)
                  ptrthis=ptrthis->ptrnext;
                  ptrthis->ptrnext=ptrnew;
                  ptrthis=ptrnew;
      }

      printf("\nenter a name:> ");
      gets(ptrthis->name);
      printf("enter a date of birth:> ");
      gets(ptrthis->dob);
      printf("enter telephone number:> ");
      gets(ptrthis->tel);
      ptrthis->ptrnext=(struct dif*)NULL;
}

void modify(void)
{
      int b;

      clrscr();
      cout<<"2: modify\n";

      if(ptrfirst==(struct dif*)NULL)
      {
            cout<<"\nthere are no structures to modify";
            wait();
      }

      else
      {
            printf("\nenter name of person to have structure modified for:> ");
            gets(temp);
            ptrthis=ptrfirst;

            do
            {
                  b=strcmp(temp,ptrthis->name);

                  if (b==0)
                  {
                        printf("\nexisting name:> %s\n",ptrthis->name);
                        printf("\nexisting date of birth:> %s\n",ptrthis->dob);
                        printf("\nexisting telephone number:> %s\n",ptrthis->tel);
                        printf("\n\nenter new/old name:> ");
                        gets(ptrthis->name);
                        printf("enter new/old date of birth:> ");
                        gets(ptrthis->dob);
                        printf("enter new/old telephone number:> ");
                        gets(ptrthis->tel);
                        wait();
                        return;
                  }

                  else
                        ptrthis=ptrthis->ptrnext;
            }while(ptrthis!=(struct dif*)NULL);

            cout<<"\nthere are currently no structures with that name to modify";
            wait();
      }
}

void del(void)
{
      int b;

      clrscr();
      cout<<"3: delete\n";

      if(ptrfirst==(struct dif*)NULL)
      {
            cout<<"\nthere are currently no structures to delete";
            wait();
      }

      else
      {
            printf("\nenter name of person to have structure deleted for:> ");
            gets(temp);
            ptrthis=ptrfirst;

            do
            {
                  b=strcmp(temp,ptrthis->name);

                  if (b==0)
                  {
                        printf("\nthis structure has now been deleted");
                        ptrfirst=ptrthis->ptrnext;
                        delete ptrfirst;
                        wait();
                        return;
                  }

                  else
                        ptrthis=ptrthis->ptrnext;
            }while(ptrthis!=(struct dif*)NULL);

            cout<<"\nthere are currently no structures with that name to delete";
            wait();
      }
}

void display()
{
      clrscr();
      cout<<"4: display\n";

      if (ptrfirst==(struct dif*)NULL)
      {
            printf("\nno structures have been entered yet");
            wait();
            return;
      }

      ptrthis=ptrfirst;

      do
      {
            printf("\nname:> %s\n",ptrthis->name);
            printf("date of birth:> %s\n",ptrthis->dob);
            printf("telephone number:> %s\n",ptrthis->tel);
            ptrthis=ptrthis->ptrnext;
      }while(ptrthis!=(struct dif*)NULL);

      wait();
}
0
Comment
Question by:njones
  • 6
  • 3
  • 2
  • +3
14 Comments
 
LVL 22

Expert Comment

by:nietod
ID: 1169922
Suggestions coming.
0
 
LVL 22

Expert Comment

by:nietod
ID: 1169923
Since you are trying to learn, I'll ofter some suggestions, not an answer, try them and get back to me.

First of all you will need two classes.  One for the linked list and another for the things in the linked list.  They will look like:

class dif;  // forward declaration because ptrfirst is a dif * before dif is defined.

class diflist
{
   dif *ptrfirst;
}

class dif
{
   char name[30];
   char dob[30];
   char tel[30];
   dif *ptrnext;

   friend diflist
};
0
 
LVL 22

Expert Comment

by:nietod
ID: 1169924
Now a couple of points.

1. the class diflist will store a linked list of dif objects.
2. the class dif was declared forward because the diflist class has a pointer to a dif, but dif hasn't been defined yet.
3.  The diflist class is declared as a friend of dif.  that allows an diflist to access private members of a dif  (if this doesn't make sense, ask).  That was done so that the diflist can access the ptrnext member of the dif class.

Now you try to make the following changes.
1.  add a constructor to the diflist class.   The constructor will initilize the diflist to have an empty linked list.  (that is the first item pointer will be NULL.)
2.  add a destructor to the diflist class.  The destructor will delete all the difs that are in the linked list.
3.  add a function to diflist that adds a new dif to the list.

Can you do these things?  Note this probably won't compile with these change, just put them in and let me know.  If you have questions ask.

If you want to e-mail me your results, my address is nietod@theshop.net.
0
 
LVL 1

Expert Comment

by:joakimf
ID: 1169925
Do you want to change your struct to a class aswell???
//joakimf
0
 

Author Comment

by:njones
ID: 1169926
Edited text of question
0
 
LVL 22

Expert Comment

by:nietod
ID: 1169927
Please don't edit the text of the question.  It makes it hard to follow the "train" of the comments.  Was the stuff I posted helpful?  do you have questions?
0
 
LVL 3

Expert Comment

by:xyu
ID: 1169928
netiod... it wold be better that you will sugest the guy Stroustrup's book on C++ (3d edition). He can find exaxt answers and examples on list's, etc. and many methodological stuff there :) (if we speaking about C++) :)
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:njones
ID: 1169929
Adjusted points to 205
0
 
LVL 22

Expert Comment

by:nietod
ID: 1169930
This is a very big topic.  There are lots of details some of them very subtle.  There are two choices:  I can post the code you want and you will not understand it.  Or I can show you how to write that code.

I would choose the second option.

I've made some suggestions do you understand them?  Do you have questions about them?  Can you do them?
0
 

Expert Comment

by:bbarnette
ID: 1169931
A struct by default is public. A class by default is private, so what I would do if you are not going to make it out into an ADT is to change the struct to a class and all the elements in it as public.
If you are going to make it into an ADT then you would have to do as nietod suggested and include a constructor with it which you should do any way with at least setting head to NULL..

Try something like:

class name
{
  ...elemnts...
 prt* next
};
0
 

Author Comment

by:njones
ID: 1169932
Adjusted points to 215
0
 
LVL 22

Expert Comment

by:nietod
ID: 1169933
njones.  what do you want?  Do you want help or do you just want someone to submit some code that works?   I've offerend to help you get this done.  If you aren't interested let me know.
0
 
LVL 1

Accepted Solution

by:
willemnel earned 210 total points
ID: 1169934
njones,

define a class like this:

class dif
{

public:
      
    char date[20];
    char name[30];
    char dob[30];
    char tel[30];
    dif *ptrnext;


    dif(){ptrnext = NULL;}      
};

Now you should be able to use your program with very litte modification. Here's a quick example:

#include <iostream.h>
#include <string.h>

class dif
{

public:
      
    char date[20];
    char name[30];
    char dob[30];
    char tel[30];
    dif *ptrnext;


    dif(){ptrnext = NULL;}      
};

void main(void)
{
    dif x,y;
   
    strcpy(x.dob,"1 April 1998");
    strcpy(y.dob,"12/6/68");

    x.ptrnext = &y;

    cout << x.dob << endl << (*x.ptrnext).dob << endl;
}

Output:

1 April 1998
12/6/68

The "dif(){ptrnext = NULL;}" in the class defenition is called a constructor and will automatically assign a NULL to the pointer when an instance of the class dif is created. That means that in the example above, x and y both will have their ptrnext's put equal to NULL upon creation. This is usefull if you want to check which item is the last one in the list (the one that isn't pointing to anything!)

A word of warning though: Altough this class will work in this setup (Experts - correct me if I'm wrong), classes can be quite tricky and you REALLY need to get yourself a good book on C++. Once you realize the power (and complexity) of Object Orientated Programming, you'll see how much your'e missing out on!

All I can say now is that (in my view) the biggest advantage of OOP is CODE RE-USE. With classes and OOP you can can save tons of work, and in a big project (containing several, if not hunderds, of thousands of line of code), you really don't have any other choice but to go the OOP way.

I hope this helps.
0
 
LVL 1

Expert Comment

by:willemnel
ID: 1169935
I forgot to mention: You can also add "dif *ptrprev" to the class definition if you wish to add a pointer that points to the previous item in the list.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Introduction This article is the first in a series of articles about the C/C++ Visual Studio Express debugger.  It provides a quick start guide in using the debugger. Part 2 focuses on additional topics in breakpoints.  Lastly, Part 3 focuses on th…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now