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;
- }
- }
- int main()
- {
- node *head,*tail;
- tail = head = NULL;
- int item,pos;
- cout<<"Enter the item : ";
- cin>>item;
- cout<<"Enter the specific position : ";
- cin>>pos;
- addNodeAtPos(head,tail,item,pos);
- }
Advertisement
Add Comment
Please, Sign In to add comment