C++ tutorial-add element to linkedlist


Structure example: building a singly linked list

Step 2: Add an element to the linked list

To add an element to the linked list, you need to consider 4 things:

1. When the list is empty, to add a new element to the list, you only let the pfirst and plast pointers point to the new item. We mark the NULL value of link of an element by crossed lines.

Add an item to the empty list  

2.If the new element is to be added to the beginning of  the list, you will need to let the link of the new item points to the pfirst and then update the pfirst to point to the new item.

Add a new element at the beginning of the list  

 3. If the new element is to be added to the middle position of the list, you need to let a pointer point to the position immediately before the position that the new element will be placed in.

Add a new item in the middle of the list  

4. If the new element is to be added to the last of the list, you need to let the link of the plast point to the new element then update the plast to point the new element.

Add the new item to the last of the list  

//C++ code to add a new element to the linked list
void Insert (int val,int pos)
{

  int t;
  ListElem *item;//new element to be inserted
  item=(ListElem *) new ListElem; //allocate space
  if(!item) {cout<<"Memory problem..."; exit(100);}

  item->data=val;

  //insert a new item to the empty list

  if(pfirst==NULL && plast==NULL){
    //The first and last item point to the new item when they are null--empty list.
     item->next=NULL;
     pfirst=item;
     plast=item;
     cout<<"Inserted: "<<item->data<<"\n";

}

//insert a new item at the beginning of the list
else if(pos==1)
{

   item->next=pfirst;
   pfirst=item;

}
//insert a new item between items
else if(pos>1 && pos<=countitem()){

  ListElem *ta;
  ta=pfirst;
  for(t=1;t<pos-1;t=t+1){ta=ta->next;} //move to the insertion point
    item->next=ta->next;
    ta->next=item;

}

//insert a new item at the end of the list
else if(pos==countitem()+1){

  item->next=NULL; //The next link of the item is null.
  plast->next=item;
  plast=item;
  cout<<"Inserted: "<<item->data<<"\n";

}
  //show message if position is not valid.
  else cout<<"Invalid position!"<<endl;


}




Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.