Haval1

insert and delete

Mar 23rd, 2019
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.02 KB | None | 0 0
  1. void addNodeAtPos(node *&head, node *&tail, int item, int pos)      //Start Function ( Insert in the specific location of list )
  2. {
  3.   node* prev = new node();
  4.   node* curr = new node();
  5.   node* newNode = new node();
  6.   newNode->data = item;
  7.  
  8.   int tempPos = 0;   // Traverses through the list
  9.  
  10.   curr = head;      // Initialize current to head;
  11.   if(head != NULL)
  12.   {
  13.     while(curr->next != NULL && tempPos != pos)
  14.     {
  15.         prev = curr;
  16.         curr = curr->next;
  17.         tempPos++;
  18.     }
  19.     if(pos==0)
  20.     {
  21.        cout << "Adding at Head! " << endl;
  22.     }
  23.     else if(curr->next == NULL && pos == tempPos+1)
  24.     {
  25.       cout << "Adding at Tail! " << endl;
  26.     }
  27.     else if(pos > tempPos+1)
  28.       cout << " Position is out of bounds " << endl;
  29.      //Position not valid
  30.  
  31.     else
  32.     {
  33.         prev->next = newNode;
  34.         newNode->next = curr;
  35.         cout << "Node added at position: " << pos << endl;
  36.     }
  37.  }
  38.  else
  39.  {
  40.     head = newNode;
  41.     newNode->next=NULL;
  42.     cout << "Added at head as list is empty! " << endl;
  43.  }
  44. }
  45. void deleteMiddleNode(node *&head,int position)     //Start Function ( Delete in the specific location of list )
  46. {
  47.     int i;
  48.     struct node *temp, *prevNode;
  49.  
  50.     if(head == NULL)
  51.     {
  52.         cout<<"List is already empty.\n";
  53.     }
  54.     else
  55.     {
  56.         temp = head;
  57.         prevNode = head;
  58.  
  59.         for(i=2; i<=position; i++)
  60.         {
  61.             prevNode = temp;
  62.             temp = temp->next;
  63.  
  64.             if(temp == NULL)
  65.                 break;
  66.         }
  67.  
  68.         if(temp != NULL)
  69.         {
  70.             if(temp == head)
  71.                 head = head->next;
  72.  
  73.             prevNode->next = temp->next;
  74.             temp->next = NULL;
  75.  
  76.             /* Delete nth node */
  77.             cout<<"\nthe item [ "<<temp->data<<" ] was delete it\n";
  78.             delete temp;
  79.  
  80.             cout<<"SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST\n";
  81.         }
  82.         else
  83.         {
  84.             cout<<"Invalid position unable to delete.\n";
  85.         }
  86.     }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment