Haval1

addByPos

Mar 20th, 2019
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1.  
  2. void addNodeAtPos(node *&head, node *&tail, int item, int pos)      //Start Function ( Insert in the specific location of list )
  3. {
  4.   node* prev = new node();
  5.   node* curr = new node();
  6.   node* newNode = new node();
  7.   newNode->data = item;
  8.  
  9.   int tempPos = 0;   // Traverses through the list
  10.  
  11.   curr = head;      // Initialize current to head;
  12.   if(head != NULL)
  13.   {
  14.     while(curr->next != NULL && tempPos != pos)
  15.     {
  16.         prev = curr;
  17.         curr = curr->next;
  18.         tempPos++;
  19.     }
  20.     if(pos==0)
  21.     {
  22.        cout << "Adding at Head! " << endl;
  23.     }
  24.     else if(curr->next == NULL && pos == tempPos+1)
  25.     {
  26.       cout << "Adding at Tail! " << endl;
  27.     }
  28.     else if(pos > tempPos+1)
  29.       cout << " Position is out of bounds " << endl;
  30.      //Position not valid
  31.  
  32.     else
  33.     {
  34.         prev->next = newNode;
  35.         newNode->next = curr;
  36.         cout << "Node added at position: " << pos << endl;
  37.     }
  38.  }
  39.  else
  40.  {
  41.     head = newNode;
  42.     newNode->next=NULL;
  43.     cout << "Added at head as list is empty! " << endl;
  44.  }
  45. }
  46.  
  47. int main()
  48. {
  49.             node *head,*tail;
  50.             tail = head = NULL;
  51.             int item,pos;
  52.             cout<<"Enter the item : ";
  53.             cin>>item;
  54.             cout<<"Enter the specific position : ";
  55.             cin>>pos;
  56.             addNodeAtPos(head,tail,item,pos);
  57. }
Advertisement
Add Comment
Please, Sign In to add comment