Tuesday, April 19, 2011

pthread example - producer/consumer

Another simple pthread example. It implements a producer/consumer pattern. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. In this pthread example, one thread produces data and another consumes it. The pthread example is shown below.


// pthread example - producer-consumer pattern.
//
#include <sys/time.h>
#include <stdio.h>
#include <pthread.h> 
#include <errno.h>

pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;

int b;  /* buffer size = 1; */ 
main()  
{
  pthread_t producer_thread; 
  pthread_t consumer_thread; 
  void *producer();
  void *consumer();
  
    pthread_create(&consumer_thread,NULL,consumer,NULL);
    pthread_create(&producer_thread,NULL,producer,NULL);
    pthread_join(consumer_thread,NULL);
}

void add_buffer(int i){
  b = i;
}
int get_buffer(){
  return b ;
}
 
void *producer()
{
int i = 0;
printf("I'm a producer\n");
while (1) {
  pthread_mutex_lock(&region_mutex);
  add_buffer(i);
  pthread_mutex_unlock(&region_mutex);
  i = i + 1;
}
pthread_exit(NULL);
}
void *consumer()
{
int i,v;
printf("I'm a consumer\n");
for (i=0;i<100;i++) {
   pthread_mutex_lock(&region_mutex);
   v = get_buffer();
   pthread_mutex_unlock(&region_mutex);
   printf("got %d  ",v);
}
pthread_exit(NULL);
}
 

pthread example - hello program

Another simple pthread example. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. The program terminates when all the threads are finished. The pthread example is shown below.


/*
 * p_hello.c -- a hello program (in pthread)
 */
#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>

#define MAX_THREAD 1000

typedef struct {
 int id;
} parm;

void *hello(void *arg)
{
 parm *p=(parm *)arg;
 printf("Hello from node %d\n", p->id);
 return (NULL);
}

void main(int argc, char* argv[]) {
 int n,i;
 pthread_t *threads;
 pthread_attr_t pthread_custom_attr;
 parm *p;

 if (argc != 2)
 {
  printf ("Usage: %s n\n  where n is no. of threads\n",argv[0]);
  exit(1);
 }

 n=atoi(argv[1]);

 if ((n < 1) || (n > MAX_THREAD))
 {
  printf ("The no of thread should between 1 and %d.\n",MAX_THREAD);
  exit(1);
 }

 threads=(pthread_t *)malloc(n*sizeof(*threads));
 pthread_attr_init(&pthread_custom_attr);

 p=(parm *)malloc(sizeof(parm)*n);
 /* Start up thread */

 for (i=0; i<n; i++)
 {
  p[i].id=i;
  pthread_create(&threads[i], &pthread_custom_attr, hello, (void *)(p+i));
 }

 /* Synchronize the completion of each thread. */

 for (i=0; i<n; i++)
 {
  pthread_join(threads[i],NULL);
 }
 free(p);
}

pthread example - basic

A simple pthread example. It just creates two threads and wait for the threads to finish. Threads are created by calling pthread_create() function. pthread_join() just waits for the specified thread to finish. The program terminates when all the threads are finished. The pthread example is shown below.



// basic pthread example.
//
#include <stdio.h>
#include <pthread.h> 
main()  {
  pthread_t f2_thread, f1_thread; 
  void *f2(), *f1();
  int i1,i2;
  i1 = 1;
  i2 = 2;
  pthread_create(&f1_thread,NULL,f1,&i1);
  pthread_create(&f2_thread,NULL,f2,&i2);
  pthread_join(f1_thread,NULL);
  pthread_join(f2_thread,NULL);
}
void *f1(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f1: %d",i);
  pthread_exit(0); 
}
void *f2(int *x){
  int i;
  i = *x;
  sleep(1);
  printf("f2: %d",i);
  pthread_exit(0); 
}

Bezier curve in C/C++

Bezier curve implementation in C. Collected from the internet (the Author is revealed below). Bezier curve is composed of two anchor points (start, end) and two control points which bends the curve like a magnet. See following code for details.



/* Subroutine to generate a Bezier curve.
    Copyright (c) 2000 David F. Rogers. All rights reserved.

    b[]        = array containing the defining polygon vertices
                  b[1] contains the x-component of the vertex
                  b[2] contains the y-component of the vertex
                  b[3] contains the z-component of the vertex
    Basis      = function to calculate the Bernstein basis value (see MECG Eq 5-65)
    cpts       = number of points to be calculated on the curve
    Fractrl    = function to calculate the factorial of a number
    j[]        = array containing the basis functions for a single value of t
    npts       = number of defining polygon vertices
    p[]        = array containing the curve points
                 p[1] contains the x-component of the point
                 p[2] contains the y-component of the point
                 p[3] contains the z-component of the point
    t          = parameter value 0 <= t <= 1
*/

#ifdef HAVE_CONFIG_H
#ifdef WIN32
#include <windows_config.h>
#else
#include <config.h>
#endif
#endif // HAVE_CONFIG_H
#include <math.h>
#include <iostream>

#ifdef _DEBUG
#include <utils/dev/debug_new.h>
#endif // _DEBUG
using namespace std;

/* function to calculate the factorial */

SUMOReal factrl(int n)
{
    static int ntop=6;
    static SUMOReal a[33]={1.0,1.0,2.0,6.0,24.0,120.0,720.0}; /* fill in the first few values */
    int j1;

    if (n < 0) { throw 1; } //cout << "\nNegative factorial in routine FACTRL\n" ;    if (n > 32) { throw 1; } //cout << "\nFactorial value too large in routine FACTRL\n";
    while (ntop < n) { /* use the precalulated value for n = 0....6 */
        j1 = ntop++;
        a[n]=a[j1]*ntop;
    }
    return a[n]; /* returns the value n! as a SUMORealing point number */
}

/* function to calculate the factorial function for Bernstein basis */

SUMOReal Ni(int n,int i)
{
    SUMOReal ni;
    ni = factrl(n)/(factrl(i)*factrl(n-i));
    return ni;
}

/* function to calculate the Bernstein basis */

SUMOReal Basis(int n,int i,SUMOReal t)
{
    SUMOReal basis;
    SUMOReal ti; /* this is t^i */
    SUMOReal tni; /* this is (1 - t)^i */

    /* handle the special cases to avoid domain problem with pow */

    if (t==0. && i == 0) ti=1.0; else ti = pow(t,i);
    if (n==i && t==1.) tni=1.0; else tni = pow((1-t),(n-i));
    basis = Ni(n,i)*ti*tni; /* calculate Bernstein basis function */
    return basis;
}

/* Bezier curve subroutine */
void
bezier(int npts, SUMOReal b[], int cpts, SUMOReal p[])
{
    int i;
    int j;
    int i1;
    int icount;
    int jcount;

    SUMOReal step;
    SUMOReal t;

    SUMOReal factrl(int);
    SUMOReal Ni(int,int);
    SUMOReal Basis(int,int,SUMOReal);

/*    calculate the points on the Bezier curve */

    icount = 0;
    t = 0;
    step = (SUMOReal) 1.0/(cpts -1);

    for (i1 = 1; i1<=cpts; i1++){ /* main loop */

        if ((1.0 - t) < 5e-6) t = 1.0;

        for (j = 1; j <= 3; j++){ /* generate a point on the curve */
            jcount = j;
            p[icount+j] = 0.;
            for (i = 1; i <= npts; i++){ /* Do x,y,z components */
                p[icount + j] = p[icount + j] + Basis(npts-1,i-1,t)*b[jcount];
                jcount = jcount + 3;
            }
        }

        icount = icount + 3;
        t = t + step;
    }
}

time measure QueryPerformanceCounter example c c++ win32

QueryPerformanceCounter() and QueryPerformanceFrequency() function provides very accurate time measure in Windows platform.QueryPerformanceFrequency() returns number of counts per second which depends on the system. QueryPerformanceCounter() returns current counter value. The accuracy is in 100us units. Time measure sample code is shown below.


// Time measure routine on Windows Platform.
//
DWORD dwEllapsedTime;
LARGE_INTEGER ilFreq;
LARGE_INTEGER ilStartTime, ilEndTime;

QueryPerformanceFrequency(&ilFreq); // counts per seconds.
QueryPerformanceCounter(&ilStartTime);

// Write your code for which to measure execution time.

QueryPerformanceCounter(&ilEndTime);

// Compute ellapsed time.
//
dwEllapsedTime = (double)((ilEndTime.QuadPart-ilStartTime.QuadPart)/(ilFreq.QuadPart/10000));

time measure in C - Windows GetTickCount() example

This time measure routine uses GetTickCount() function of Windows. Thought it does not give exact CPU cycles of the code fragment, you can get a rough real-life measurement from this. Time measure routine using GetTickCount() is shown below.
 


 
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This program shows example of Getting Elapsed Time#include <iostream>
#include <Windows.h>
using namespace std;

unsigned long startTime_;

void startTime()
{
  startTime_ = GetTickCount();
}

unsigned int calculateElapsedTime()
{
  unsigned int diffInMilliSeconds = GetTickCount() - startTime_;
  return diffInMilliSeconds;
}

int main()
{
  //Increasing the accuracy of Sleep to 1ms using timeBeginPeriod  timeBeginPeriod(1); //Add Winmm.lib in Project  unsigned int diffTime = 0, lastTime = 0, newTime = 0;
  startTime();
  cout<<"Start Time = "<<calculateElapsedTime()<<endl;

  Sleep(100);
  newTime = calculateElapsedTime();
  diffTime = newTime - lastTime;
  cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
  lastTime = newTime;

  Sleep(100);
  newTime = calculateElapsedTime();
  diffTime = newTime - lastTime;
  cout<<"Time after 100ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
  lastTime = newTime;

  Sleep(5);
  newTime = calculateElapsedTime();
  diffTime = newTime - lastTime;
  cout<<"Time after   5ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;
  lastTime = newTime;

  Sleep(50);
  newTime = calculateElapsedTime();
  diffTime = newTime - lastTime;
  cout<<"Time after  50ms Sleep = "<<newTime<<", Difference = "<<diffTime<<endl;

  timeEndPeriod(1); //Must be called if timeBeginPeriod() was called  return 0;
}

Time measure in C - clock() function

This C time measure example code that uses clock() function.Though clockt() function does not exactly count the number of cycles, it provides real-life numbers for performance of the code fragment. Note: In Windows, you can also use GetTickCount() function for time measure.



// Time measure routine using clock() function.
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>

int main() {
clock_t start, stop;
double t = 0.0;

/* Start timer */
assert((start = clock())!=-1);

/* Do lotsa fancy calculations */

/* Stop timer */
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC;

printf("Run time: %f\n", t);

return(0);
} /* main */

shouldAutorotateToInterfaceOrientation example objc objective c

By default, shouldAutorotateToInterfaceOrientation returns YES for the UIInterfaceOrientationPortrait orientation only. If your view controller supports additional orientations, override this method and return YES for all orientations it supports. Your implementation of shouldAutorotateToInterfaceOrientation should simply return YES or NO based on the value in the interfaceOrientation parameter. Do not attempt to get the value of the interfaceOrientation property or check the orientation value reported by the UIDevice class. Your view controller is either capable of supporting a given orientation or it is not

iPhone supports four rotation modes.

UIInterfaceOrientationPortrait
UIInterfaceOrientationPortraitUpsideDown
UIInterfaceOrientationLandscapeLeft
UIInterfaceOrientationLandscapeRight



If you want only "Portrait mode". You can use following code.


- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


If you want to support all the orientation.


- (BOOL)shouldAutorotateToInterfaceOrientation:

(UIInterfaceOrientation)interfaceOrientation {

return YES;

}



If you want to support some of the orientations, you can write

 (here Portrait, landscapeLeft, landscapeRight)


- (BOOL)shouldAutorotateToInterfaceOrientation:

(UIInterfaceOrientation)interfaceOrientation {

return (interfaceOrientation == UIInterfaceOrientationPortrait ||

interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||

interfaceOrientation == UIInterfaceOrientationLandscapeRight);

}

Just returning YES in this method isn't enough, you should also set auto-size parameters of the view in the interface builder.

Eulerian Path example c++

Eulerian Path Posted by yasith at 10:55 AM Content quoted from  http://www.tuxv.net/2007/05/eulerian-path.html I'm going to jump to Eulerian Path in this post. My Program uses a recursive function to get the Eulerian Path for a given graph. For those who don't know what Eulerian Path is.

"Eulerian path is a path in a graph which visits each edge exactly once. Similarly, an Eulerian circuit is an Eulerian path which starts and ends on the same vertex"

If there is to be an Eulerian path for a given graph the graph must have lesser than three nodes with odd number of edges. If there are two nodes with odd number of edges the Euler walk must begin in an odd node and end with the other odd node.he algorithm is an example of dynamic programming.

This graph can't have an Eulerian Path.



But this graph can have an Eulerian Path.



You can download the eulerwalk.cpp file by clicking on the link.


#include <iostream>
#include <list>

using namespace std;

int graph[100][100];
int n, x, y, steps;
list<int> path;

void walk(int pos){
for(int i = 0; i < n; i++){
    if(graph[pos][i] > 0){
             graph[pos][i] --;
             graph[i][pos] --;
             walk(i);
             break;
    }
}
path.push_back(pos+1);

}

int main(){

cin >> n;
for(int i = 0; i < n; i++){
  cin >> x >> y;
  graph[x-1][y-1] ++; //we are using zero index 
}
walk(0);
while(!path.empty()){
    cout << path.back() << ' ';
    path.pop_back();
}
}

Floyd Warshall - Shortest Path Algorithm in C++

Another version of Shortest Path Algorithm in C++. It is a graph analysis algorithm for finding shortest paths in a weighted graph (with positive or negative edge weights). A single execution of the algorithm will find the lengths (summed weights) of the shortest paths between all pairs of vertices though it does not return details of the paths themselves. The algorithm is an example of dynamic programming.



#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
class path
{
    int n;
        int p[10][10];
        int a[10][10];
        int c[10][10];
    public:
        void get();
        void pm();
        void ap();
        void disp();
};
void path::get()
{
    int i,j,k;
    clrscr();
    cout<<"Enter the no. of nodes in the graph :";
    cin>>n;
    cout<<"
Enter the adjacency matrix :
";
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            //    cout<<"a["<<i<<","<<j<<"] = ";
            cin>>a[i][j];
            p[i][j]=0;
        }
    }
    cout<<"

Enter The cost matrix is :

";
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
           //    cout<<"a["<<i<<","<<j<<"] = ";
            cin>>c[i][j];
        }
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {

                p[i][j]=a[i][j];

        }
    }
}
void path::disp()
{
//    cout<<"

 The output matrix for the given graph is :
";
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cout<<p[i][j]<< "    ";
        }
        cout<<endl;
}
}

void path::pm()
{
    int i,j,k;

    for(k=1;k<=n;k++)
    {
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                p[i][j]=p[i][j] || p[i][k] && p[k][j];
            }
        }
    }

}
void path::ap()
{
    int i,j,k;
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {

                p[i][j]=c[i][j];

        }
    }
    for(k=1;k<=n;k++)
    {
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=n;j++)
            {
                if(p[i][j]<p[i][k]+p[k][j])
                {
                    p[i][j]=p[i][j];
                }
                else
                {
                p[i][j]=p[i][k]+p[k][j];
                }
            }
        }
    }
}
void main()
{
path p;
p.get();
p.pm();
cout<<"path matrix is :
";
p.disp();
getch();
p.ap();
cout<<"all pair shortest  path matrix is :
";
p.disp();
getch();
}

Dijkstra - Shortest Path Algorithm in C++

Dijkstra's shortest path algorithm in C++. It's one of the most popular graph processing algorithm. You can tweak a little to reverse the operation; i.e. to compute the longest path (simple take reciprocal of the path weight). Below is a C++ class implementing Dijkstra's Shortest Path Algorithm.



class Dijkstra
    {        
        private int rank = 0;
        private int[,] L;
        private int[] C; 
        public int[] D;
        private int trank = 0;
        public Dijkstra(int paramRank,int [,]paramArray)
        {
            L = new int[paramRank, paramRank];
            C = new int[paramRank];
            D = new int[paramRank];
            rank = paramRank;
            for (int i = 0; i < rank; i++)
            {
                for (int j = 0; j < rank; j++) {
                    L[i, j] = paramArray[i, j];
                }
            }

            for (int i = 0; i < rank; i++)
            {
                C[i] = i;
            }
            C[0] = -1;          
            for (int i = 1; i < rank; i++)
                D[i] = L[0, i];
        }
        public void DijkstraSolving()
        {            
            int minValue = Int32.MaxValue;
            int minNode = 0;
            for (int i = 0; i < rank; i++)
            {
                if (C[i] == -1)
                    continue;
                if (D[i] > 0 && D[i] < minValue)
                {
                    minValue = D[i];
                    minNode = i;
                }
            }
            C[minNode] = -1;
            for (int i = 0; i < rank; i++)
            { 
                if (L[minNode, i] < 0)
                    continue;
                if (D[i] < 0) {
                    D[i] = minValue + L[minNode, i];
                    continue;
                }
                if ((D[minNode] + L[minNode, i]) < D[i])
                    D[i] = minValue+ L[minNode, i];
            }
        }
        public void Run()
        {
            for (trank = 1; trank >rank; trank++)
            {
                DijkstraSolving();
                Console.WriteLine("iteration" + trank);
                for (int i = 0; i < rank; i++)
                    Console.Write(D[i] + " ");
                Console.WriteLine("");
                for (int i = 0; i < rank; i++)
                    Console.Write(C[i] + " ");
                Console.WriteLine("");                
            }
        }
 }

Doubly Linked List example C++

Collected from Web. Generic Doubly-Linked List (C++) by Bench on Jul 18th, 2007. This code snippet outlines a simple, no-frills linked list. Tested under MSVC++ 2003 and Comeau, but not guaranteed bug free. Snippet includes example main() .

This snippet is intended as an example of a possible implementation of a linked list class (Of which there are many variations) For a better linked list, use the STL <list> library.


(Doubly Linked List example)


  1. #include <iostream>
  2.  
  3. template <typename T>
  4. class double_linked
  5. {
  6. struct node
  7. {
  8. T data;
  9. node* prev;
  10. node* next;
  11. node(T t, node* p, node* n) : data(t), prev(p), next(n) {}
  12. };
  13. node* head;
  14. node* tail;
  15. public:
  16. double_linked() : head( NULL ), tail ( NULL ) {}
  17. template<int N>
  18. double_linked( T (&arr) [N]) : head( NULL ), tail ( NULL )
  19. {
  20. for( int i(0); i != N; ++i)
  21. push_back(arr[i]);
  22. }
  23. bool empty() const { return ( !head || !tail ); }
  24. operator bool() const { return !empty(); }
  25. void push_back(T);
  26. void push_front(T);
  27. T pop_back();
  28. T pop_front();
  29. ~double_linked()
  30. {
  31. while(head)
  32. {
  33. node* temp(head);
  34. head=head->next;
  35. delete temp;
  36. }
  37. }
  38. };
  39. template <typename T>
  40. void double_linked<T>::push_back(T data)
  41. {
  42. tail = new node(data, tail, NULL);
  43. if( tail->prev )
  44. tail->prev->next = tail;
  45. if( empty() )
  46. head = tail;
  47. }
  48. template <typename T>
  49. void double_linked<T>::push_front(T data)
  50. {
  51. head = new node(data, NULL, head);
  52. if( head->next )
  53. head->next->prev = head;
  54. if( empty() )
  55. tail = head;
  56. }
  57. template<typename T>
  58. T double_linked<T>::pop_back()
  59. {
  60. if( empty() )
  61. throw("double_linked : list empty");
  62. node* temp(tail);
  63. T data( tail->data );
  64. tail = tail->prev ;
  65. if( tail )
  66. tail->next = NULL;
  67. else
  68. head = NULL ;
  69. delete temp;
  70. return data;
  71. }
  72. template<typename T>
  73. T double_linked<T>::pop_front()
  74. {
  75. if( empty() )
  76. throw("double_linked : list empty");
  77. node* temp(head);
  78. T data( head->data );
  79. head = head->next ;
  80. if( head )
  81. head->prev = NULL;
  82. else
  83. tail = NULL;
  84. delete temp;
  85. return data;
  86. }
  87. int main()
  88. {
  89. int arr[] = { 4, 6, 8, 32, 19 } ;
  90. double_linked<int> dlist ( arr );
  91. dlist.push_back( 11 );
  92. dlist.push_front( 100 );
  93. while( dlist )
  94. std::cout << dlist.pop_back() << " ";
  95. }

Singly linked list code example C++

Singly Linked List is an data structure where items are linked in one direction. It usually takes following structure. A example implementation of Singly Linked List  is shown below. (It's collected from web-surfing. I forgot the source site.)

     Header -> first node -> second node -> ... -> Nth node.
                           |                   |                         |
                        data1            data2                   dataN



#include<iostream.h>
#include<conio.h>
#include<stdlib.h>


class list
{
    struct node
    {
        int data;
        node *link;
    }*p;
public:
    void inslast(int);
    void insbeg(int);
    void insnext(int,int);
    void delelement(int);
    void delbeg();
    void dellast();
    void disp();
    int seek(int);
    list(){p=NULL;}
    ~list();
};

void list::inslast(int x)
{
    node *q,*t;
    if(p==NULL)
    {
        p=new node;
        p->data=x;
        p->link=NULL;
    }
    else
    {
        q=p;
        while(q->link!=NULL)
            q=q->link;
        t=new node;
        t->data=x;
        t->link=NULL;
        q->link=t;
    }
    cout<<"
 Inserted successfully at the end..
";
    disp();
}

void list:: insbeg(int x)
{
    node *q;
    q=p;
    p=new node;
    p->data=x;
    p->link=q;
    cout<<"
 Inserted successfully at the begining..
";
    disp();
}


void list::delelement(int x)
{
    node *q,*r;
    q=p;
    if(q->data==x)
    {
        p=q->link;
        delete q;
        return;
    }
    r=q;
    while(q!=NULL)
    {
        if(q->data==x)
        {
            r->link=q->link;
            delete q;
            return;
        }
        r=q;
        q=q->link;
    }
    cout<<"
 Element u entered   "<<x<<"    is not found..
";
}

void list:: delbeg()
{
    cout<<"
 The list before deletion:
";
    disp();
    node *q;
    q=p;
    if(q==NULL)
    {
        cout<<"
 No data is present..
";
        return;
    }
    p=q->link;
    delete q;
    return;
}


void list:: dellast()
{
    cout<<"
 The list before deletion:
";
    disp();
    node *q,*t;
    q=p;
    if(q==NULL)
    {
        cout<<"
 There is no data in the list..
";
        return;
    }
    if(q->link==NULL)
    {
        p=q->link;
        delete q;
        return;
    }

    while(q->link->link!=NULL)
        q=q->link;
    q->link=NULL;
    return;
}

list::~list()
{
    node *q;
    if(p==NULL) return;
    while(p!=NULL)
    {
        q=p->link;
        delete p;
        p=q;
    }
}

void list::disp()
{
    node *q;
    q=p;
    if(q==NULL)
    {
        cout<<"
 No data is in the list..
";
        return;
    }
    cout<<"
 The items present in the list are :
";
    while(q!=NULL)
    {
        cout<<"    "<<q->data;
        q=q->link;
    }
}

void list :: insnext(int value,int position)
{
    node *temp,*temp1;
    temp=p;
    if(temp1==NULL)
    {
        temp1= new node;
        temp1->data=value;
        temp1->link=NULL;
        p=temp1;
        return;
    }
    for(int i=0;((i<position)&&(temp->link!=NULL)) ;i++)
    {
        if(i==(position-1))
        {
            temp1= new node;
            temp1->data= value;
            temp1->link=temp->link;
            temp->link=temp1;
        }
        temp=temp->link;
    }
    //cout<<"
 Inserted successfully at the position.."<<position;
    disp();
}


int list::seek(int value)
{
    node *temp;
    temp=p;
    int position=0;
    while(temp!=NULL)
    {
        if(temp->data==value)
            return position+1;
        else
        {
            temp=temp->link;
            position=position+1;
        }
    }
    cout<<"

 Element "<<value<<" not found";
    return 0;
}


void main()
{
list l;
int ch,v,p,ps;
do
{
    clrscr();
    cout<<"
 Operations on List..
";
    cout<<"
1.Insertion
2.Deletion
3.Display
4.Seek
5.Exit";
    cout<<"
 Enter ur choice:";
    cin>>ch;

    switch(ch)
    {
    case 1:
        cout<<"
1.Insertion at begining
2.Insertion at the end
";
        cout<<"3.Insertion after the mentioned position
";
        cout<<"
 Enter ur choice:";
        cin>>ps;
        cout<<"
 Enter the value to insert:";
        cin>>v;
        switch(ps)
        {
            case 1:
                l.insbeg(v);
                break;
            case 2:
                l.inslast(v);
                break;
            case 3:
                cout<<"
 Enter the position to insert the value:";
                cin>>p;
                l.insnext(v,p);
                break;

            default:
                cout<<"
 The choice is invalid
";
                return;
        }
    break;

    case 2:
        cout<<"
1.Delete the first element
2.Delete the last element";
        cout<<"
3.Enter the element to delete from the list";
        cout<<"
 Enter ur choice:";
        cin>>ps;
        switch(ps)
        {
            case 1:
                l.delbeg();
                cout<<"
 The list after deletion:
";l.disp();
                break;
            case 2:
                l.dellast();
                cout<<"
 The list after deletion:
";l.disp();
                break;
            case 3:
                l.disp();
                cout<<"
 Enter the element to delete :    ";
                cin>>v;
                l.delelement(v);
                cout<<"
 The list after deletion:
";l.disp();
                break;

            default:
                cout<<"
 The option is invalid...
";
                break;
        }
    break;

    case 3:
        l.disp();
        break;

    case 4:
        l.disp();
        cout<<"
 Enter the element to search:";
        cin>>v;
        cout<<"
 The position of the element "<< v<<"  is "<<l.seek(v);
        getch();
        break;

    case 5:
        exit(1);

    default:
        cout<<"
 The option is invalid...
";
        return;
    }
    getch();
}while(ch!=5);
getch();
return;
}