Linked List (LinkedList.cpp)


/ Published in: C++
Save to your folder(s)

Not working.


Copy this code and paste it in your HTML
  1. #include "LinkedList.h"
  2. #include "LinkedNode.h"
  3.  
  4. template < class T >
  5. LinkedList< T >::LinkedList()
  6. {
  7. size = 0;
  8. }
  9.  
  10. template < class T >
  11. void LinkedList< T >::add( T value )
  12. {
  13. // first set up our node
  14. LinkedNode * node = new LinkedNode( this, firstNode, &value );
  15.  
  16. if( firstNode == NULL )
  17. {
  18. // this node is the first one in our list
  19. firstNode = node;
  20. }
  21.  
  22. //and our size got increased by one
  23. size++;
  24. }
  25.  
  26. //unnecessary function?
  27. /* set the currentNode pointer to a new node
  28. void LinkedList::setCurrentNode( int nodeNumber )
  29. {
  30. // start from the first node
  31. LinkedNode * node = this->firstNode;
  32.  
  33. // then go through the links until we reach the node we want
  34. for( int i = 0; i < nodeNumber; i++ )
  35. {
  36. node = node->next();
  37. }
  38.  
  39. // set the node as the current node
  40. this->currentNode = node;
  41. }
  42. */
  43.  
  44. template < class T >
  45. void LinkedList< T >::remove( T value )
  46. {
  47. // start at the first node
  48. LinkedNode< T > * node = firstNode;
  49.  
  50. // go through the links until we find the value that matches
  51. while( node->value() != value )
  52. {
  53. node = node->next();
  54. }
  55.  
  56. //link over this node before we remove it
  57. node->previous()->setNextNode( node->next() );
  58.  
  59. //now we can remove this node
  60. delete node;
  61. node = NULL;
  62.  
  63. //and our size just got decreased by one
  64. size--;
  65. }
  66.  
  67. template < class T >
  68. void LinkedList< T >::removeByIndex( int index )
  69. {
  70. //start with the first node
  71. LinkedNode< T > * node = firstNode;
  72.  
  73. //go through the nodes until we get to the one we want
  74. for( int i = 0; i < index; i++ )
  75. {
  76. node = node->next();
  77. }
  78.  
  79. //now we have to link over this node
  80. node->previous()->setNextNode( node->next() );
  81.  
  82. // remove the node
  83. delete node;
  84. node = NULL;
  85.  
  86. // and our size got decreased by one
  87. size--;
  88. }
  89.  
  90. template < class T >
  91. T LinkedList< T >::get( int index )
  92. {
  93. // start with the first node
  94. LinkedNode< T > * node = firstNode;
  95.  
  96. // go through the nodes until we get to the one we want
  97. for( int i = 0; i < index; i++ )
  98. {
  99. node = node->next();
  100. }
  101.  
  102. //return the node's value
  103. return *( node->getValue() );
  104. }
  105.  
  106. template < class T >
  107. int LinkedList< T >::getSize()
  108. {
  109. return size;
  110. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.