Adrita

task 3( ds lab 6) 3rd sem

Mar 17th, 2020
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct node
  4. {
  5. int data;
  6. struct node *next;
  7. struct node *prev;
  8. };
  9. typedef struct node Node;
  10. Node* create_node(int item, Node *next,Node*prev)
  11. {
  12. Node* new_node=new Node();
  13. if(new_node==NULL)
  14. cout<<"Error"<<endl;
  15. else
  16. {
  17. new_node->data=item;
  18. new_node->next=next;
  19. new_node->prev=prev;
  20. }
  21. return new_node;
  22.  
  23. }
  24. Node* prepend(int item,Node* head)
  25. {
  26. Node* new_node=create_node(item,head,NULL);
  27. return new_node;
  28. }
  29. Node* append(int item,Node *head)
  30. {
  31. Node *new_node=create_node(item,NULL,NULL);
  32. if(head==NULL)
  33. return new_node;
  34. else
  35. {
  36. Node* current=new Node();
  37. current=head;
  38. while(current->next!=NULL)
  39. current=current->next;
  40. current->next=new_node;
  41. new_node->prev=current;
  42. }
  43. return head;
  44. }
  45. Node* insertn(int item,Node* head,int key)
  46. {
  47. Node* new_node=create_node(item,NULL,NULL);
  48. if(head==NULL)
  49. cout<<"Error"<<endl;
  50. else
  51. {
  52. Node *current=new Node();
  53. current=head;
  54. while(current!=NULL&&current->data!=key)
  55. current=current->next;
  56. if(current!=NULL)
  57. {
  58. new_node->next=current->next;
  59. current->next=new_node;
  60. new_node->prev=current;
  61. }
  62. else
  63. cout<<"Value not found"<<endl;
  64. }
  65. return head;
  66. }
  67. void display(Node *head)
  68. {
  69. cout<<"Linked list:"<<endl;
  70. while(head!=NULL)
  71. {
  72. cout<<head->data<<" ";
  73. head=head->next;
  74. }
  75. cout<<endl;
  76. }
  77.  
  78. int main()
  79. {
  80. Node*head=NULL;
  81. int t;
  82. cout<<"Number of test cases"<<endl;
  83. cin>>t;
  84. for(int i=0; i<t; i++)
  85. {
  86. cout<<"Enter 1 to prepend, 2 to append and 3 to insert"<<endl;
  87. int n;
  88. cin>>n;
  89. cout<<"Enter the value"<<endl;
  90. int item;
  91. cin>>item;
  92. if(n==1)
  93. {
  94. head=prepend(item,head);
  95. display(head);
  96. }
  97. else if(n==2)
  98. {
  99. head=append(item,head);
  100. display(head);
  101. }
  102. else if(n==3)
  103. {
  104. cout<<"Enter the key"<<endl;
  105. int key;
  106. cin>>key;
  107. head=insertn(item,head,key);
  108. display(head);
  109. }
  110. }
  111. }
Add Comment
Please, Sign In to add comment