﻿ C exercises and solutions: add element

# C exercises and solutions: add element

Step 2: Add an element to the circularly linked list To add an element to the circularly 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.

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.

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.

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.

Note: After the new item was inserted to the list, the next link of the plast is pointed to the pfirst. By doing this, all items of the list are linked together circularly.

void Insert (int val,int pos)
{
int t,val_pos=1;
ListElem *item;//new element to be inserted
item=(ListElem *)malloc(sizeof(ListElem)); //allocate space
if(!item) {printf("Memory problem..."); exit(100);}
item->data=val;
//insert a new item to the empty Circularly Linked List
if(pfirst==NULL && plast==NULL){
//The first and last item point to the new item when they are   null--empty Circularly Linked List.
pfirst=item;
plast=item;
printf("Inserted:%d",item->data);printf("\n");
}
//insert a new item at the beginning of the Circularly Linked List
else if(pos==1)
{
item->next=pfirst;
pfirst=item;
}
//insert a new item between items
else if(pos>1 && pos<=countitem(pfirst)){
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 Circularly Linked List
else if(pos==countitem(pfirst)+1){
plast->next=item;
plast=item;
printf("Inserted:%d",item->data);printf("\n");
}
//show message if position is not valid.
else {val_pos=0;printf("%s %d %s","Invalid position! Position must be between 1 and ",countitem(pfirst)+2,"\n");}
if(val_pos!=0 && plast!=NULL) plast->next=pfirst; //let the plast points to the pfirst to make the list curcularly linked

}