C++ exercises and solutions-Element of singly linkedlist-OOP

Element of singly linked list

Step 1: Define element of the singly linked list

The linked list element has two parts--data and pointer or link. Therefore, we define the the element of the linked list by using a class that has two members--data and next pointer.

C single linked list

//C++ code to define list element

template <class Type> class LinkedList;

template <class Type>
class ListElem {
ListElem (const Type elem){next=NULL; val=elem;}
Type val; // the element data
ListElem *next; // next link

The list elements are chained together in the linked list. Therefore, we need another class called LinkedList that provides few useful methods to operate the linked list.

//C++ code to define the LinkedList class and its members
template <class Type>
class LinkedList {
void Insert (const Type&,int);
void Delete(int);//delete item from the list
void printall();//print out all items on the screen
int countitem();//return the number of items in the list
ListElem<Type> *pfirst; // first element in the list
ListElem<Type> *plast; // last element in the list


template <class Type>
LinkedList<Type>::~LinkedList (void)
ListElem<Type> *item;
ListElem<Type> *next;
for(item =pfirst; item!= NULL; item= next){
next = item->next;
delete item;



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.