Tuesday, April 19, 2011

Doubly Linked List example C++

Collected from Web. Generic Doubly-Linked List (C++) by Bench on Jul 18th, 2007. This code snippet outlines a simple, no-frills linked list. Tested under MSVC++ 2003 and Comeau, but not guaranteed bug free. Snippet includes example main() .

This snippet is intended as an example of a possible implementation of a linked list class (Of which there are many variations) For a better linked list, use the STL <list> library.


(Doubly Linked List example)


  1. #include <iostream>
  2.  
  3. template <typename T>
  4. class double_linked
  5. {
  6. struct node
  7. {
  8. T data;
  9. node* prev;
  10. node* next;
  11. node(T t, node* p, node* n) : data(t), prev(p), next(n) {}
  12. };
  13. node* head;
  14. node* tail;
  15. public:
  16. double_linked() : head( NULL ), tail ( NULL ) {}
  17. template<int N>
  18. double_linked( T (&arr) [N]) : head( NULL ), tail ( NULL )
  19. {
  20. for( int i(0); i != N; ++i)
  21. push_back(arr[i]);
  22. }
  23. bool empty() const { return ( !head || !tail ); }
  24. operator bool() const { return !empty(); }
  25. void push_back(T);
  26. void push_front(T);
  27. T pop_back();
  28. T pop_front();
  29. ~double_linked()
  30. {
  31. while(head)
  32. {
  33. node* temp(head);
  34. head=head->next;
  35. delete temp;
  36. }
  37. }
  38. };
  39. template <typename T>
  40. void double_linked<T>::push_back(T data)
  41. {
  42. tail = new node(data, tail, NULL);
  43. if( tail->prev )
  44. tail->prev->next = tail;
  45. if( empty() )
  46. head = tail;
  47. }
  48. template <typename T>
  49. void double_linked<T>::push_front(T data)
  50. {
  51. head = new node(data, NULL, head);
  52. if( head->next )
  53. head->next->prev = head;
  54. if( empty() )
  55. tail = head;
  56. }
  57. template<typename T>
  58. T double_linked<T>::pop_back()
  59. {
  60. if( empty() )
  61. throw("double_linked : list empty");
  62. node* temp(tail);
  63. T data( tail->data );
  64. tail = tail->prev ;
  65. if( tail )
  66. tail->next = NULL;
  67. else
  68. head = NULL ;
  69. delete temp;
  70. return data;
  71. }
  72. template<typename T>
  73. T double_linked<T>::pop_front()
  74. {
  75. if( empty() )
  76. throw("double_linked : list empty");
  77. node* temp(head);
  78. T data( head->data );
  79. head = head->next ;
  80. if( head )
  81. head->prev = NULL;
  82. else
  83. tail = NULL;
  84. delete temp;
  85. return data;
  86. }
  87. int main()
  88. {
  89. int arr[] = { 4, 6, 8, 32, 19 } ;
  90. double_linked<int> dlist ( arr );
  91. dlist.push_back( 11 );
  92. dlist.push_front( 100 );
  93. while( dlist )
  94. std::cout << dlist.pop_back() << " ";
  95. }