View Single Post
Join Date: Jun 2006
Posts: 147
Reputation: Laiq Ahmed will become famous soon enough Laiq Ahmed will become famous soon enough 
Solved Threads: 20
Laiq Ahmed Laiq Ahmed is offline Offline
Junior Poster

Re: Not repeated elements in link list (help)

 
0
  #6
Dec 4th, 2008
Originally Posted by lmastex View Post
Sorry I forgot ( I remember I used them though) Anyways.
The problem is that when I make an insertion of an element, I don't want to insert a repeated element, so if I inserted (Age = 20) and then If I insert (Age = 20) my list should have only one person who Age is 20, i don't want two ages of 20 in my list. Insertion without repeating elements.

  1. template <typename ListElement>
  2. void List <ListElement>::Insert()
  3. {
  4. NodePtr Ptr;
  5. Ptr = new Node;
  6. bool repeated = true;
  7.  
  8. if (Ptr == NULL)
  9. {
  10. cout << "Error: Insuficient Storage " << endl;
  11. exit(1);
  12. }
  13.  
  14. cout << " Enter The Social Security Number of New Student: ";
  15. cin >> Ptr->Info.SSN;
  16. cout << "Enter The Age of This Student: ";
  17. cin >> Ptr->Info.Age;
  18.  
  19. while( Ptr->Next != NULL)
  20. {
  21. if(Ptr->Info.Age == Ptr->Next->Info.Age)
  22. repeated = false;
  23. break; // This break is for not to add the element
  24.  
  25. Ptr = Ptr->Next;
  26.  
  27.  
  28. }
  29.  
  30. Ptr->Next = Head;
  31. Head = Ptr;
  32.  
  33. if(repeated = false)
  34. cout << "repetition just ocurred" << endl; // This is just 4 me to verified if the function works
  35.  
  36.  
  37.  
  38. }
I've changed your code
  1. template <typename ListElement>
  2. void List <ListElement>::Insert()
  3. {
  4. NodePtr Ptr;
  5. Ptr = new Node;
  6. bool repeated = false;
  7.  
  8. if (Ptr == NULL)
  9. {
  10. cout << "Error: Insuficient Storage " << endl;
  11. exit(1);
  12. }
  13.  
  14. cout << " Enter The Social Security Number of New Student: ";
  15. cin >> Ptr->Info.SSN;
  16. cout << "Enter The Age of This Student: ";
  17. cin >> Ptr->Info.Age;
  18.  
  19. while( Ptr->Next != NULL)
  20. {
  21. if(Ptr->Info.Age == Ptr->Next->Info.Age) {
  22. repeated = true;
  23. break;
  24. }
  25. // This break is for not to add the element
  26. Ptr = Ptr->Next;
  27. }
  28.  
  29. if(repeated = false) {
  30. Ptr->Next = Head;
  31. Head = Ptr;
  32. }
  33. else {
  34. delete Ptr;
  35. cout << "repetition just ocurred" << endl; // This is just 4 me to verified if the function works
  36. }


Hope Above idea helps
Reply With Quote