Linked List using STL


The standard template library provides a container for lists (it is a doubly linked lists). There are many functions available and the following program shows a few of them:

//A program to illustrate the STL container for linked lists

#include <iostream>
#include <list>
using namespace std;

int main( )
{
list<int> intlist;
list<int>::iterator ptr;
int i;

//checking whether the list is empty
if (intlist.empty( )= =true)
{
cout<<endl<<"The list is empty";
}

//adding 5 values to the list (0 1 2 3 4)
for( i = 0; i<5; i++)
{
intlist.push_back( i );
}

//adding another element (4) to the list
intlist.push_back(4);

//initializing the iterator to the first node
//displaying the value held in the first node

ptr=intlist.begin( );
cout<<endl<<"First element has value: "<<*ptr;

//traversing through the list by incrementing the iterator
cout<<endl<<"Initial list contents are : ";
for (i = 0; ptr != intlist.end( ); i++)
{
cout<<" "<<*ptr; //displaying the value at that node
ptr++;
}

//removing duplicate elements from the list
intlist.unique( );

cout<<endl<<"Modified list contents are: ";
ptr = intlist.begin( );
for (i=0; ptr!=intlist.end( ); i++)
{
cout<<" "<<*ptr;
ptr++;
}

return 0;
}

The output will be:

The list is empty

First element has value: 0

Initial list contents are : 0 1 2 3 4 4

Modified list contents are: 0 1 2 3 4

Let’s just take a look at some of the functions used in the above program:

                list<int> intlist;

                list<int>::iterator ptr;

Here we are creating a linked list named ‘intlist’ and we are also creating an iterator named ‘ptr’. An iterator is similar to a pointer and it is used to store addresses.

                intlist.empty( )

This functions returns a bool value (true or false) depending on whether the list is empty or not.

                intlist.push_back(i);

push_back(data) is used to insert an element to the end of the list. There is also a pop_back ( ) function to remove the last element of the list. Or you can use the push_front (data) to insert data at the start of the list.

                ptr = intlist.begin( )

This function returns a reference to the first node of the linked list. In our program we have stored this value in the iterator ‘ptr’. The function intlist.end( ) is the converse of begin( ).

                intlist.unique( );

The unique( ) function removes any duplicate values occurring later on in the list.

There are lots of in-built functions that you can try out on linked lists. This program was meant to give you an idea of how to use these functions.


Learn in the next section about Stacks.

Go back to Contents page 2.


Copyright © 2004 Sethu Subramanian All rights reserved.