Tag Archives: linkedlist

LinkedList : creation and manipulation

LinkedList is a data structure consisting of a group of nodes .In its simplest form, each node contains a data element and a link or reference  to the next node in the sequence . Because of this structure  insertion or removal of elements from any position in the list becomes very easy.

linkedlist-randomtechbits

linkedlist code for creation and list manipulation

Here is the c++ code which can create a link list and allows the user to perform various operations on linked list like  inserting element, delete,reversing the linked list , counting the number of elements etc to manipulate it:

CODE:

/*
 http://randomtechbits.in/
*Program to various operations on linked list of integers
*code tested on devc++ IDE
*/

#include
#include
#include
using namespace std;

struct node
{int data;
node *link;
}*P;

void add(int NUM)
{
node *temp,*q;
if(P==NULL)
  {P=new node ;
   P->data=NUM;
   P->link=NULL;
  }
else
  {q=P;
  while(q->link!=NULL)q=q->link;
  temp=new node;
  temp->data=NUM;
  temp->link=NULL;
  q->link=temp;
  }
}

void display()
{node *q;
q=P;
while(q!=NULL)
  {
  cout<data<<"\n";   q=q->link;
  }
}
void del(int NUM)
{node *q,*prev=NULL;
q=P;
while(q->data!=NUM&&q!=NULL)
  {prev=q;
   q=q->link;
  }
if(q==NULL)cout<<"\nElement does not exist in the list";
 else   {prev->link=q->link;
  delete(q);
  }
}

void reverse()
{node *q,*temp,*next;
if(P==NULL)return;
q=P->link;
P->link=NULL;
while(q!=NULL)
  {temp=q->link;
  q->link=P;
  P=q;
  q=temp; 
  }
}
int count()
{int count=0 ;node *q=P;
while(q!=NULL){q=q->link;++count;}
return count;
}

int nthfromend(int INDEX)
{node *i,*j,*prev;
int current=0,n=0,len,ifromend;
i=P;
len=count();
ifromend=len+1-INDEX;
if(INDEX<0||INDEX>len)
 {cout<<"invalid INDEX\n";  } else for(i=P;i!=NULL;i=i->link)
  {if(current==ifromend){return i->data;}
   current++;  
  }
}

main()
{P=NULL;
node *temp;
int OPTION;
while(true)
{cout<<"Select the operation u want to perform on linked list:\n1.Add Element\n2.Delete Element\n3.Display()\n4.Reverse List\n5.Find nth element from end\n6.Count number of Elements in list\n7.Exit\n\n"; cin>>OPTION;
switch(OPTION)
 {
 case 1:int NUM;
        cout<<"Enter the element to add:\n";         cin>>NUM;
        add(NUM);
        break;
 case 2:
        cout<<"Enter the element to delete:\n";         cin>>NUM;
        add(NUM);
        break;
 case 3:display();
        break;
 case 4:reverse();
        break;
 case 5:int INDEX;
        cout<<"Enter INDEX:\n";         cin>>INDEX;
        cout<<INDEX<<"th element fomr end"<<nthfromend(INDEX)<<"\n";
        break;
 case 6:cout<<"There are "<<count()<<" elments in the list\n";
        break;
 case 7:exit(0);
 default:cout<<"u entered invalid option";
 }
}
getch();
}