Wednesday, March 28, 2018

Write a C++ program to illustrate list and list operations


AIM: Write a C++ program to illustrate list and list operations
THEORY:
List
Lists are sequence containers that allow constant time insert and erase operations anywhere within the sequence, and iteration in both directions.

List containers are implemented as doubly-linked lists; Doubly linked lists can store each of the elements they contain in different and unrelated storage locations. The ordering is kept internally by the association to each element of a link to the element preceding it and a link to the element following it.

They are very similar to forward_list: The main difference being that forward_list objects are single-linked lists, and thus they can only be iterated forwards, in exchange for being somewhat smaller and more efficient.

Compared to other base standard sequence containers (
arrayvector and deque), lists perform generally better in inserting, extracting and moving elements in any position within the container for which an iterator has already been obtained, and therefore also in algorithms that make intensive use of these, like sorting algorithms.

The main drawback of lists and forward_lists compared to these other sequence containers is that they lack direct access to the elements by their position; For example, to access the sixth element in a list, one has to iterate from a known position (like the beginning or the end) to that position, which takes linear time in the distance between these. They also consume some extra memory to keep the linking information associated to each element (which may be an important factor for large lists of small-sized elements).

SOURCE CODE:
#include<iostream>
#include<list>
using namespace std;
void show(list<int>&num)
{
            list<int>::iterator n;
            for(n=num.begin();n!=num.end();++n)          
{
                        cout<<*n<<"";
            }
}
int main()
{
            list<int>list;
            list.push_back(5);
            list.push_back(10);
            list.push_back(15);
            list.push_back(20);
            cout<<"\n number are:-";
            show(list);
            cout<<"\n interest elements at the begining of list";
            list.push_front(25);
            cout<<"\n after inserting elements are:";
            show(list);
            cout<<"\n delete elements at the begining";
            list.pop_front();
            cout<<"\n delete least elements";
            list.pop_back();
            cout<<"\n after deleting numbers are:";
            show(list);
            cout<<"\n elements in reverse order:";
            list.reverse();
            show(list);
            return 0;
}

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home