Advertisement
Guest User

Untitled

a guest
Apr 19th, 2018
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.24 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. using namespace std;
  4.  
  5.  
  6. typedef struct element{
  7. int key;
  8. struct element *next;
  9. struct element *prev;
  10. }node;
  11.  
  12. node *head=NULL;
  13. node *tail=NULL;
  14.  
  15. void addhead(node **head,node **tail, int key){
  16. node *nowa =(node*)malloc(sizeof(node));
  17. nowa->key=key;
  18. nowa->next=NULL;
  19. nowa->prev=NULL;
  20. if(*head == NULL){
  21. *head = nowa;
  22. *tail = nowa;
  23. }else{
  24. (*head)->prev=nowa;
  25. nowa->next = *head;
  26. *head = nowa;
  27. }
  28. }
  29. void addtail(node **head, node**tail, int key){
  30. node *nowa = (node*)malloc(sizeof(node));
  31. nowa->key=key;
  32. nowa->next = NULL;
  33. nowa->prev = NULL;
  34.  
  35. if(*tail == NULL){
  36. *head = nowa;
  37. *tail = nowa;
  38. }else{
  39. (*tail)->next = nowa;
  40. nowa->prev = *tail;
  41. *tail = nowa;
  42. }
  43. }
  44.  
  45. void printListFromHead(node *head){
  46. if(head!=NULL){
  47. cout << head->key << " ";
  48. printListFromHead(head->next);
  49. }
  50. }
  51.  
  52. void printListFromTail(node *head){
  53. if(head!=NULL){
  54. printListFromTail(head->next);
  55. cout << head->key << " ";
  56. }
  57. }
  58.  
  59. unsigned int listSize(node *head){
  60. unsigned int size = 0;
  61. while(head!=NULL){
  62. size++;
  63. head = head->next;
  64. }
  65. return size;
  66. }
  67.  
  68. void removeHead(node **head, node **tail){
  69. if(*head!=NULL){
  70. if(*head == *tail){
  71. *head = NULL;
  72. *tail = NULL;
  73. }else{
  74. node *tmp = *head;
  75. (*head) = (*head)->next;
  76. if(*head!=NULL){
  77. (*head)->prev = NULL;
  78. }
  79. free(tmp);
  80. }
  81. }
  82. }
  83.  
  84. void removeTail(node **head, node **tail){
  85. if(*tail!=NULL){
  86. if(*tail == *head){
  87. *tail = NULL;
  88. *head = NULL;
  89. }else{
  90. node *tmp = *tail;
  91. (*tail) = (*tail)->prev;
  92. if(*tail!=NULL){
  93. (*tail)->next = NULL;
  94. }
  95. free(tmp);
  96. }
  97. }
  98. }
  99.  
  100.  
  101.  
  102. int main(){
  103. int rando;
  104. for(int i=0; i<5; i++){
  105. rando = rand()%100+1;
  106. addhead(&head,&tail,rando);
  107. rando = rand()%100+1;
  108. addtail(&head,&tail,rando);
  109. }
  110. cout << "List printed from head: " << endl;
  111. printListFromHead(head);
  112. cout << endl;
  113. cout << "List printed from tail: " << endl;
  114. printListFromTail(head);
  115. cout << endl;
  116. cout << "Number of elements in list: "<< listSize(head);
  117. cout << endl;
  118. for(int i = 0; i < 3; i++){
  119. removeHead(&head, &tail);
  120. removeTail(&head, &tail);
  121. }
  122. printListFromHead(head);
  123. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement