bishalbiswas

given node

Sep 8th, 2014
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. //INSERT SPECIFIC
  2. /**** Program to Insert at Specific Node in a Linked List ****/
  3. #include <stdio.h>
  4. #include<malloc.h>
  5. #include<iostream>
  6. using namespace std;
  7. void insert_last();
  8. void insert_specific();
  9. void display();
  10. struct node
  11. {
  12. int info;
  13. struct node *link;
  14. } *start=NULL;
  15. int item;
  16.  
  17. int main()
  18. {
  19. int ch;
  20. do
  21. {
  22. printf("\n\n\n1. Insert Last\n2. Insert Specific\n3. Display\n4.Exit\n");
  23. printf("\nEnter your choice: ");
  24. scanf("%d", &ch);
  25. switch(ch)
  26. {
  27. case 1:
  28. insert_last();
  29. break;
  30. case 2:
  31. insert_specific();
  32. break;
  33. case 3:
  34. display();
  35. break;
  36. case 4:
  37. return 0;
  38. default:
  39. printf("\n\nInvalid choice. Please try again.\n");
  40. }
  41. } while (1);
  42. }
  43.  
  44.  
  45. void insert_last()
  46. {
  47. struct node *ptr;
  48. printf("\n\nEnter item: ");
  49. scanf("%d", &item);
  50. if(start == NULL)
  51. {
  52. start = (struct node *)malloc(sizeof(struct node));
  53. start->info = item;
  54. start->link = NULL;
  55. }
  56. else
  57. {
  58. ptr = start;
  59. while (ptr->link != NULL)
  60. ptr = ptr->link;
  61. ptr->link = (struct node *)malloc(sizeof(struct node));
  62. ptr = ptr->link;
  63. ptr->info = item;
  64. ptr->link = NULL;
  65. }
  66. printf("\nItem inserted: %d\n", item);
  67. }
  68.  
  69. void insert_specific()
  70. {
  71. int n;
  72. struct node *newn, *ptr;
  73. if (start == NULL)
  74. printf("\n\nLinked list is empty. It must have at least onenode.\n");
  75. else
  76. {
  77. printf("\n\nEnter INFO after which new node is to be inserted: ");
  78. scanf("%d", &n);
  79. printf("\n\nEnter ITEM: ");
  80. scanf("%d", &item);
  81. ptr = start;
  82. newn = start;
  83.  
  84. while (ptr != NULL)
  85. {
  86. if (ptr->info == n)
  87. {
  88. newn = (struct node *)malloc(sizeof(struct node));
  89. newn->info = item;
  90. newn->link = ptr->link;
  91. ptr->link = newn;
  92. printf("\n\nItem inserted: %d", item);
  93. return;
  94. }
  95. else
  96. ptr = ptr->link;
  97. }
  98. }
  99. }
  100.  
  101. void display()
  102. {
  103. struct node *ptr = start;
  104. int i=1;
  105. if (ptr != NULL)
  106. {
  107.  
  108. while(ptr != NULL)
  109. {
  110.  
  111. printf("\n Sr. No.\tAddress\t\tInfo\t\tLink\n\n%d.\t\t%d\t\t%d\t\t%d\n", i, ptr, ptr->info,ptr->link);
  112. ptr = ptr->link;
  113. i++;
  114. }
  115. }
  116. else
  117. {
  118. printf("\nLinklist is empty.\n");
  119.  
  120. }
  121. }
Advertisement
Add Comment
Please, Sign In to add comment