views:

137

answers:

2

DEAR All;

Hi, I'm just beginner to C++; Please help me to understand:

What functions should be in the Linked list class ? I think there should be overloaded operators << and >>; Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal.

Edit: This is only first stage, the next one will be (hopefully) with templates.

Please review the small code for the integer List (enclosed MyNODE.h and ListDriver1.cpp); MyNODE.h

    // This is my first attempt to write linked list. Igal Spector, June 2010.

#include <iostream.h>
#include <assert.h>

//Forward Declaration of the classes:
class ListNode;
class TheLinkedlist;

// Definition of the node (WITH IMPLEMENTATION !!!, without test drive):


class ListNode{
 friend class TheLinkedlist;
public:
 // constructor:
 ListNode(const int& value, ListNode *next= 0);
 // note: no destructor, as this handled by TheLinkedList class.

 // accessor: return data in the node.
// int Show() const {return theData;}

private:
 int theData;  //the Data
 ListNode* theNext; //points to the next node in the list.
};

//Implementations:
//constructor:
inline ListNode::ListNode(const int &value,ListNode *next)
:theData(value),theNext(next){}


//end of ListNode class, now for the LL class:

class TheLinkedlist
{
public:
 //constructors:
 TheLinkedlist();
 virtual ~TheLinkedlist();
 // Accessors:
 void InsertAtFront(const &);
 void AppendAtBack(const &);

// void InOrderInsert(const &);
 bool IsEmpty()const;//predicate function
 void Print() const;
private:
 ListNode * Head; //pointer to first node
 ListNode * Tail; //pointer to last node.
};

//Implementation:

//Default constructor
inline TheLinkedlist::TheLinkedlist():Head(0),Tail(0) {}

//Destructor
inline TheLinkedlist::~TheLinkedlist(){
 if(!IsEmpty()){  //list is not empty
 cout<<"\n\tDestroying Nodes"<<endl;
 ListNode *currentPointer=Head, *tempPtr;

  while(currentPointer != 0){ //Delete remaining Nodes.
   tempPtr=currentPointer;
  cout<<"The node: "<<tempPtr->theData <<" is Destroyed."<<endl<<endl;
  currentPointer=currentPointer->theNext;
  delete tempPtr;
  }
 Head=Tail = 0;  //don't forget this, as it may be checked one day.
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::InsertAtFront(const int& value){
 ListNode *newPtr = new ListNode(value,Head);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  newPtr->theNext = Head;
  Head = newPtr;
 }
}

//Insert the Node to the beginning of the list:
void TheLinkedlist::AppendAtBack(const int& value){
 ListNode *newPtr = new ListNode(value, NULL);
 assert(newPtr!=0);

 if(IsEmpty())  //list is empty
  Head = Tail = newPtr;
 else {    //list is NOT empty
  Tail->theNext = newPtr;
  Tail = newPtr;
 }
}

//is the list empty?
inline bool TheLinkedlist::IsEmpty() const
  { return (Head == 0); }

// Display the contents of the list
void TheLinkedlist::Print()const{
 if ( IsEmpty() ){
  cout << "\n\t The list is empty!!"<<endl;
  return;
 }

 ListNode *tempPTR = Head;
 cout<<"\n\t The List is: ";

 while ( tempPTR != 0 ){
  cout<< tempPTR->theData <<"  ";
  tempPTR = tempPTR->theNext;
 }
 cout<<endl<<endl;
}
//////////////////////////////////////

The test Driver:

//Driver test for integer Linked List.

#include <iostream.h>
#include "MyNODE.h"

// main Driver
int main(){

 cout<< "\n\t This is the test for integer LinkedList."<<endl;

 const int arraySize=11,
   ARRAY[arraySize]={44,77,88,99,11,2,22,204,50,58,12};

 cout << "\n\tThe array is: "; //print the numbers.
 for (int i=0;i<arraySize; i++)
  cout<<ARRAY[i]<<",  ";

 TheLinkedlist list;   //declare the list

 for(int index=0;index<arraySize;index++)
  list.AppendAtBack( ARRAY[index] );//create the list

 cout<<endl<<endl;
 list.Print();    //print the list

 return 0;     //end of the program.
}
+7  A: 

What functions should be in the Linked list class ?

That depends on what you need to do with it. At the very least, one should probably be able to add elements to it, and to look at the elements in the list.

(This is common sense. Because if you can't modify or read your list in any way, what could it ever be used for?)


I think there should be overloaded operators << and >>;

Why? What would they do? I suppose you mean operator << to do insertion, similar to how objects are inserted into C++ IO streams; but what exactly should operator >> do? Extraction/removal of elements of some sort? If you implement insertion and extraction (?) in this manner, probably noone will be able to understand your linked list class. A linked list is not an IO stream. (Those operators with IO streams were chosen for brevity.)

I would advise you against operator overloading if the meaning of the operation is not clear. I would suggest you name your operations more explicitly, e.g. by providing methods add and remove (I'm still guessing at the meaning of the latter operation >> btw.).


Please help me to improve the code (style, errors, etc,) Thanks for advance. Igal.

I don't want to make this the main point on my answer, so just very briefly off the top of my head, some issues:

  • You should #include <iostream> instead of #include <iostream.h>, and then either add a using namespace std; or write (e.g.) std::cout instead of cout.

  • Try to get rid of the friend. You should be able to design your classes in a way that doesn't require this. friend is easily misused to get around proper encapsulation. But encapsulation is something you should definitely think about in OOP.

  • Though that's not an advice to give to a C++ beginner, if you made your linked list class into a template class, it could store different values than just ints. Just take this as a hint for future improvements.


And finally:

  • Just use the STL ("Standard Template Library") containers which are included in the C++ standard library. I know that "rolling your own" helps understanding how these data structures work, but be aware that the C++ standard library already includes a solid and efficient set of data containers.
stakx
This a million times. Just use std::list<T>.
DeadMG
Dear stakx and DeadMG.Thanks for your answer and comment.I forgot to mention that template List<T> will be the next topic I'll study.I'm appreciate your answer and involvement, You know Internet is still a marvel to me, how people help each other !
Igal Spector
+1  A: 
  1. 0 should be NULL

  2. inline only in the case that you don't care that your code will be public, usually implementation puts in separate file Mylist.cpp file.

  3. Why your destructor virtual, do you have inheritance ?

  4. You can just define struct node instead separate class its better define your list for practice like in stl. http://www.sgi.com/tech/stl/List.html http://www.cplusplus.com/reference/stl/list/

In C++ common to use vector vs linked list in Java http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html

Yosef
*0 should be NULL:* This is not correct. The literal `0` denotes both the null pointer as well as the number zero. I concede that `NULL` perhaps causes less confusion; nevertheless writing `0` for the null pointer is perfectly legal. (In fact, `NULL` is often defined as a macro resolving to something like `((void*)0)`.
stakx
C++ proper design style is to use NULL instead 0
Yosef