Advertisement
Dark_Shard

Linked List(Nth Position insertion[wip])

Aug 6th, 2019
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include<iostream>
  2.  
  3. using namespace std;
  4.  
  5. struct sampleStruct{
  6.     string data;
  7.     sampleStruct* next;
  8. };
  9.  
  10. sampleStruct* head = NULL;
  11.  
  12. void pushData( string data)
  13. {
  14.     sampleStruct* newData = new sampleStruct;
  15.     newData->data = data;
  16.     newData->next = head;
  17.     head = newData;
  18. }
  19.  
  20. void insertData(int pos, string data)
  21. {
  22.     sampleStruct* newData  = new sampleStruct;
  23.     sampleStruct* temp = head;
  24.  
  25.     if(pos == 1)
  26.     {
  27.  
  28.         head = newData;
  29.         head->data = data;
  30.         head->next = temp;
  31.  
  32.     }
  33.     else{
  34.         for(int a = 1 ; a < pos-1 ; a++)
  35.         {
  36.             temp = temp->next;
  37.         }
  38.  
  39.  
  40.     }
  41. }
  42.  
  43. void printData()
  44. {
  45.     sampleStruct* temp = head;
  46.     while(temp!= NULL)
  47.     {
  48.         cout << temp->data << endl;
  49.         temp = temp->next;
  50.     }
  51. }
  52.  
  53.  
  54.  
  55. int main()
  56. {
  57.     string name = " ";
  58.     int pos = 0;
  59.     cout << "Input minimum of 5" << endl;
  60.     for(int a = 0; a < 5 ; a++)
  61.     {
  62.         cout << "Input name " <<  a << endl;
  63.         cin >> name;
  64.         pushData(name);
  65.     }
  66.     cout << "These are your inputs " << endl;
  67.     cout << endl;
  68.     printData();
  69.  
  70.     while(1)
  71.     {
  72.  
  73.     cout << "Input name and the position to insert at" << endl;
  74.     cout << "Input name" << endl;
  75.     cin >> name;
  76.     cout << "Input pos" << endl;
  77.     cin >> pos;
  78.     insertData(pos , name);
  79.     cout <<" After insertion " <<endl;
  80.  
  81.     printData();
  82.  
  83.     }
  84.  
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement