Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. struct Node{
  4. int data;
  5. struct Node *next;
  6. };
  7. void Insert(struct Node **head,int position,int x)
  8. {
  9. //cout<<(head)<<" "<<(*head)<<"\n";
  10. struct Node *p,*q,*newNode;
  11. newNode=new Node();
  12. newNode->data=x;
  13. p=*head;
  14. if(position==1)
  15. {
  16. newNode->next=p;
  17. //cout<<newNode<<endl;
  18. *head=newNode;
  19. return;
  20. }
  21. else
  22. {
  23. int k=1;
  24. while(p!=NULL && k<position)
  25. {
  26. k++;
  27. q=p;
  28. p=p->next;
  29. }
  30. q->next=newNode;
  31. newNode->next=p;
  32. }
  33. }
  34. void Delete(struct Node **head,int position)
  35. {
  36. struct Node *p,*q;
  37. p=*head;
  38. //cout<<(head)<<" "<<(*head)<<"\n";
  39. if(*head==NULL)
  40. {
  41. cout<<"List empty!!\n";
  42. return;
  43. }
  44.  
  45. if(position==1)
  46. {
  47. *head=(*head)->next;
  48. free(p);
  49. return;
  50. }
  51. else
  52. {
  53. int k=1;
  54. while(p!=NULL && k<position)
  55. {
  56. k++;
  57. q=p;
  58. p=p->next;
  59. }
  60. if(p==NULL)
  61. {
  62. cout<<"Position not found!!\n";
  63. return;
  64. }
  65. else
  66. {
  67. q->next=p->next;
  68. delete(p);
  69. }
  70. }
  71. }
  72. void Print(struct Node **head)
  73. {
  74. struct Node *p=*head;
  75. while(p)
  76. {
  77. cout<<p->data<<" ";
  78. p=p->next;
  79. }
  80. cout<<"\n";
  81. }
  82. int main()
  83. {
  84. struct Node *head=NULL;
  85. //cout<<head<<"\n";
  86. Insert(&head,1,5);
  87. Insert(&head,1,4);
  88. Insert(&head,3,3);
  89. Insert(&head,2,2);
  90. Insert(&head,2,1);
  91. Print(&head);
  92.  
  93. Delete(&head,1);
  94. Print(&head);
  95. Delete(&head,4);
  96. //Delete(&head,1);
  97. Print(&head);
  98. Delete(&head,4);
  99. Print(&head);
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement