Advertisement
Adrita

task 1 ( ds lab 6) 3rd sem

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