fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. struct node *head = NULL;
  5.  
  6. struct node{
  7. int num;
  8. struct node* next;
  9. };
  10.  
  11. void append(int n){
  12. struct node* p = (struct node*)malloc(sizeof(struct node));
  13. struct node* temp = head;
  14. p->num = n;
  15. p->next = NULL;
  16. if(head==NULL){
  17. head = p;
  18. }
  19. else{
  20. while(temp->next!=NULL){
  21. temp = temp->next;
  22. }
  23. temp->next = p;
  24. }
  25. }
  26.  
  27. void del(int pos){
  28. if(head==NULL)
  29. cout << "The list is empty" << endl;
  30. else if(pos==1){
  31. struct node* temp = head;
  32. head = head->next;
  33. free(temp);
  34. }
  35. else{
  36. struct node* curr = head;
  37. struct node* prev = head;
  38. for(int i=1; i<pos; i++){
  39. prev = curr;
  40. if(curr->next==NULL){
  41. cout << "You have inserted wrong value for deletion" << endl;
  42. exit(1);
  43. }
  44. else
  45. curr = curr->next;
  46. }
  47. prev->next = curr->next;
  48. free(curr);
  49. }
  50. }
  51.  
  52. void display(){
  53. if(head == NULL)
  54. cout << "The list is empty" << endl;
  55. else{
  56. struct node* temp = head;
  57. while(temp!=NULL){
  58. cout << temp->num << " " << endl;
  59. temp = temp->next;
  60. }
  61. cout << "------***------" << endl ;
  62. }
  63. }
  64.  
  65. void insert(int pos, int n){
  66. struct node* p = (struct node*)malloc(sizeof(struct node));
  67. struct node* curr = head;
  68. struct node* prev = head;
  69. for(int i=1; i<pos; i++){
  70. prev = curr;
  71. if(curr==NULL){
  72. cout << "You have inserted wrong position for insertion" << endl;
  73. exit(1);
  74. }
  75. else
  76. curr = curr->next;
  77. }
  78. p->next = curr;
  79. p->num = n;
  80. prev->next = p;
  81. }
  82.  
  83. void search(int n){
  84. struct node* temp = head;
  85. if(head==NULL)
  86. cout << "The list is empty" << endl;
  87. else{
  88. int i=1;
  89. while(temp!=NULL){
  90. if(temp->num==n){
  91. cout << i << endl;
  92. break;
  93. }
  94. temp=temp->next;
  95. i++;
  96. }
  97. if(temp==NULL)
  98. cout << "Element cannot be found" << endl;
  99. }
  100. }
  101.  
  102. int main(){
  103. display();
  104. append(1);
  105. append(2);
  106. append(3);
  107. insert(4, 4);
  108. display();
  109. search(5);
  110. }
Success #stdin #stdout 0s 4368KB
stdin
Standard input is empty
stdout
The list is empty
1 
2 
3 
4 
------***------
Element cannot be found