View Single Post
Join Date: Nov 2008
Posts: 32
Reputation: Ahmed_I is an unknown quantity at this point 
Solved Threads: 1
Ahmed_I Ahmed_I is offline Offline
Light Poster

Genreic Double Linked List Using Templates

 
0
  #1
Nov 22nd, 2008
Generic Double Linked List
  1. /* These are generic Functions for a Generic List
  2.  * Note:-Only Functions not including a Menu and an Interface
  3.  * You could use these Functions for your own Benefit*/
  4. #include <iostream>
  5. using namespace std;
  6. template <class X> struct node{ //Template Structure
  7. X data;
  8. node* next;
  9. node* prev;
  10. };
  11.  
  12. template <class Y> void insert_first(node<Y>** l,Y elem)
  13. {
  14. node<Y>* Q=new node<Y>();
  15. Q->data=elem;
  16. Q->prev=NULL;
  17. Q->next=*l;
  18. *l=Q;
  19. }
  20. template <class Y> void print_l(node<Y>* l)//Print the List
  21. {
  22. while(l!=NULL)
  23. {
  24. cout<<l->data<<" ";
  25. l=l->next;
  26. }
  27. }
  28. template <class type> int count(node<type>* l)//Count the List
  29. {
  30. int counter=0;
  31. while(l!=NULL)
  32. {
  33. counter++;
  34. l=l->next;
  35. }
  36. return counter;
  37. }
  38.  
  39. template <class type> void append(node<type>** l,type elem)
  40. {
  41. if(*l==NULL)
  42. insert_first(&*l,elem);
  43. else
  44. {
  45. node<type>*temp=*l;
  46. node<type> *Q=new node<type>;
  47. Q->data=elem;
  48. while(temp->next!=NULL)
  49. {
  50. temp=temp->next;
  51. }
  52. temp->next=Q;
  53. Q->prev=temp;
  54. }
  55. }
  56. template <class type>
  57. void insert_at_pos(node<type> **l,int pos,type elem)
  58. {
  59. if(pos<=0||pos>count(*l))
  60. {
  61. cout<<"Invalid Position"<<endl;
  62. exit(1);
  63. }
  64. node<type>* Q=new node<type>;
  65. node<type>* temp=*l;
  66. int i=2;
  67. if(pos==1)
  68. {
  69. insert_first(&*l,elem);
  70. }
  71. else
  72. {
  73. while(temp!=NULL)
  74. {
  75. if(pos==i)
  76. {
  77. Q->data=elem;
  78. Q->next=temp->next;
  79. Q->prev=temp;
  80. temp->next=Q;
  81. }
  82. i++;
  83. temp=temp->next;
  84. }
  85. }
  86. }
  87.  
  88. int main(int argc, char** argv)
  89. {
  90. node<int>* q=NULL;//Create Empty Pointer that Will point to the Head of the List
  91. insert_first(&q,2);
  92. insert_at_pos(&q,2,2);
  93. return 0;
  94. }

If there is any critique about this code plz tell me about it to be careful in the next time i write any code .
Reply With Quote