Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void addNodeAtPos(node *&head, node *&tail, int item, int pos) //Start Function ( Insert in the specific location of list )
- {
- node* prev = new node();
- node* curr = new node();
- node* newNode = new node();
- newNode->data = item;
- int tempPos = 0; // Traverses through the list
- curr = head; // Initialize current to head;
- if(head != NULL)
- {
- while(curr->next != NULL && tempPos != pos)
- {
- prev = curr;
- curr = curr->next;
- tempPos++;
- }
- if(pos==0)
- {
- cout << "Adding at Head! " << endl;
- }
- else if(curr->next == NULL && pos == tempPos+1)
- {
- cout << "Adding at Tail! " << endl;
- }
- else if(pos > tempPos+1)
- cout << " Position is out of bounds " << endl;
- //Position not valid
- else
- {
- prev->next = newNode;
- newNode->next = curr;
- cout << "Node added at position: " << pos << endl;
- }
- }
- else
- {
- head = newNode;
- newNode->next=NULL;
- cout << "Added at head as list is empty! " << endl;
- }
- }
- void deleteMiddleNode(node *&head,int position) //Start Function ( Delete in the specific location of list )
- {
- int i;
- struct node *temp, *prevNode;
- if(head == NULL)
- {
- cout<<"List is already empty.\n";
- }
- else
- {
- temp = head;
- prevNode = head;
- for(i=2; i<=position; i++)
- {
- prevNode = temp;
- temp = temp->next;
- if(temp == NULL)
- break;
- }
- if(temp != NULL)
- {
- if(temp == head)
- head = head->next;
- prevNode->next = temp->next;
- temp->next = NULL;
- /* Delete nth node */
- cout<<"\nthe item [ "<<temp->data<<" ] was delete it\n";
- delete temp;
- cout<<"SUCCESSFULLY DELETED NODE FROM MIDDLE OF LIST\n";
- }
- else
- {
- cout<<"Invalid position unable to delete.\n";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment