Advertisement
Guest User

Untitled

a guest
Jul 28th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.25 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node {
  5. int data;
  6. struct node *next;
  7. struct node *prev;
  8. };
  9.  
  10. void push(struct node **head_ref, int new_data){
  11. struct node *new_node = (struct node*) malloc(sizeof(struct node));
  12. new_node->data = new_data;
  13. new_node->next = *head_ref;
  14. new_node->prev = NULL;
  15. if(*head_ref != NULL){
  16. (*head_ref)->prev = new_node;
  17. }
  18. *head_ref = new_node;
  19. return;
  20. }
  21.  
  22. /* Given a node as next_node, insert a new node before the given node */
  23. void insertBefore(struct node** next_node, int new_data){
  24.  
  25. // 1. check if the given next_node is NULL
  26. if(*next_node == NULL){
  27. cout<<"given node is NULL"<<endl;
  28. return;
  29. }
  30. // 2. allocate new node
  31. struct node* new_node = (struct node*)malloc(sizeof(struct node));
  32. // 3. put data in node
  33. new_node->data = new_data;
  34.  
  35. // 4. case: if next_node id head
  36. if((*next_node)->prev == NULL){
  37. cout<<"inside into"<<endl;
  38. (*next_node)->prev = new_node;
  39. new_node->next = *next_node;
  40. new_node->prev = NULL;
  41. // setting new head
  42. *next_node = new_node;
  43. return;
  44. }
  45.  
  46. // 5. set new_node's next & prev
  47. new_node->next = *next_node;
  48. new_node->prev = (*next_node)->prev;
  49.  
  50. cout<<"(*next_node)->data"<<(*next_node)->data<<endl;
  51.  
  52. //*****************?????QUESTION??????****************
  53. // WHY THIS BELOW CODE CHANGING DATA (*next_node)->data 3 ???
  54. new_node->prev->next = new_node;
  55.  
  56. cout<<"(*next_node)->data"<<(*next_node)->data<<endl;
  57. (*next_node)->prev = new_node;
  58.  
  59. return;
  60. }
  61.  
  62. void printList(struct node *node)
  63. {
  64. struct node *last;
  65. cout<<"nTraversal in forward direction n";
  66. while (node != NULL)
  67. {
  68. cout<<" "<< node->data;
  69. last = node;
  70. node = node->next;
  71. }
  72.  
  73. cout<<"nTraversal in reverse direction n";
  74. while (last != NULL)
  75. {
  76. cout<<" "<<last->data;
  77. last = last->prev;
  78. }
  79.  
  80. return;
  81. }
  82.  
  83. int main() {
  84.  
  85. struct node* head = NULL;
  86. push(&head, 8);
  87. push(&head, 4);
  88. push(&head, 7);
  89. push(&head, 1);
  90.  
  91. // Insert 3, before 7. So linked list becomes 1->3->7->8->4->NULL
  92. insertBefore(&(head->next), 3);
  93. cout<<"Created DLL is: ";
  94. printList(head);
  95.  
  96. return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement