Friday, March 14, 2014

LINKED LIST in C++

Linkedlist have one data storing part and one pointer . basic operation like adding deleting can be performed easily. linked list has one head-starting and tail -last end.pointer points to the next unit.
last pointer is NULL usually.
code in C++ is given below.

basic structure is shown in diagram.




#include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
int input(node *L)
{
int d;
cout<<"enter a value";
cin>>d;
node *K;
L->data=d;
while(d!=-1)
      {
      K=new(node);
L->next=K;
L=K;
cout<<"enter a value";
cin>>d;
L->data=d;
}
if(d==-1)
L->next=NULL;
}

void addafter(node *L,int k,int m)
{
node *T;
while(L->data!=k)
{
L=L->next;
}
L->next=T;
L=T;
L=new(node);
L->data=m;
L->next=T;
}
int out(node *L)
{while(L!=NULL){
if(L->data!=-1)
cout<<" "<<L->data;
L=L->next;}
}
int addend(node *L)
{node *K;
while(L->next!=NULL)
{L=L->next;
}
K=new(node);
int d;
L->next=K;
K=L;
cout<<"enetr the number to inserted at end";
cin>>d;
L->data=d;
L->next=NULL;
}
int main()
{ int d,b,n;
node *L,*K,*t;
L=new(node);
K=L;
input(L);
L=K;
addend(L);
K=L;
cout<<"after which element you want to insert";
cin>>b;
cout<<"input";
int x;
cin>>x;
node *s;
addafter(L,b,x);
out(L);
return 0;
}


No comments:

Post a Comment

Contributors

Translate