August 17, 2010

Entry to the linked list using c++


 class ListEntry  
 {  
 char* listvalue;  
 ListEntry* preventry;  
 public:  
 ListEntry(char*);  
 ~ListEntry()  
 { delete [] listvalue; }  
 ListEntry* PrevEntry() const  
 { return preventry; };  
 void display() const  
 { std::cout << std::endl << listvalue; } // Use the 'this' pointer to chain the list. void AddEntry(ListEntry& le)  
  {  
 le.preventry = this;  
  }  
  }; // The constructor definition.  
 ListEntry::ListEntry(char* s)  
 {  
 listvalue = new char[std::strlen(s)+1];  
 std::strcpy(listvalue, s);  
 preventry = 0;  
 }  
 int main()  
 {  
  ListEntry* prev = 0; // Read in some names.  
 while (1)  
  {  
 std::cout << std::endl << "Enter a name ('end' when done): ";  
 char name[25]; std::cin >> name;  
 if (std::strncmp(name, "end", 3) == 0)  
 break;  
 // Make a list entry of the name.  
 ListEntry* list = new ListEntry(name);  
 // Add the entry to the linked list.  
 if (prev != 0)  
 prev->AddEntry(*list);  
 prev = list;  
 }  
 // Display the names in reverse order.  
 while (prev != 0)  
 {  
 prev->display();  
 ListEntry* hold = prev;  
 prev = prev->PrevEntry();  
 // Delete the ListEntry object.  
 delete hold;  
 }  
 return 0;  
 }