Guest User

LinkedList.cpp

a guest
Jan 23rd, 2016
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. /*
  2. Implement a linked list.
  3. Write a C++ class (or set of classes) that implements a linked list. The data contained in the nodes are integers.
  4. The maximum number of nodes in the list is 100. Implement at least the following functions:
  5. · Constructor and destructor;
  6. · void insert (int number); - inserts an element with the value number at the beginning of the list;
  7. · int isEmpty(); - returns 1 if the list is empty, 0 otherwise;
  8. · int numOfElements(); - returns the number of elements in the list.
  9. */
  10.  
  11. linkedList::linkedList()
  12. {
  13. root = NULL;
  14. max_size = 100; // LL size can't go beyond this
  15. size = 0; //Initial size
  16. }
  17.  
  18. void linkedList::insert(int number)
  19. {
  20. if (size == max_size || 100)
  21. {
  22. printf("FUll!\n");
  23. }
  24. else
  25. {
  26. if (size == 0) // If the size is 0 (empty LL), create a new node with avalue
  27. {
  28. root = new node(number, NULL);
  29. }
  30. else //Otherwise, point to the next node
  31. {
  32. node* newNode = new node(number, root);
  33. root = newNode;
  34.  
  35. }
  36. size++;//Increments the size by 1 each iteration
  37. printf("The item has successfully been added to the list!\n");//Notifies the user that the item has been added successfully!
  38. }
  39. }
  40.  
  41.  
  42. int linkedList::isEmpty() // Checks if the LL is empty or not
  43. {
  44. if (size == 0){
  45. return 1;
  46. }
  47. else
  48. return 0;
  49. }
  50. int linkedList::numOfElements() // Checks to see how many elements are in the LL
  51. {
  52. return size;
  53. }
  54. void linkedList::printList() // Prints but will not return a value
  55. {
  56. node* temp = root;
  57. if (size == 0)
  58. return 1;
  59. else
  60. {
  61. printf("%f ", root->data);
  62. }
  63. while (temp->next != NULL)
  64. {
  65. temp = temp->next; // temp is assigned to the next value from the pointer
  66. printf("%f ", temp->data);
  67.  
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment