Saturday, 27 August 2011

Searching particular node in single Linked List

The following is the logic to find the particular node in the SLL
template<class T>
T sll<T>::find(int i)
{
 node<T> *p;
 if(i<1||i>length())
  return(-1);
 else//optional
 p=first;
 for(int j=1;j<=i-1;j++)
  p=p->link;
 return(p->data);

}


//find the data in particular node in the sll
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
template<class T>
class sll;
template<class T>
class node
{
 private:
  T data;
  node<T>* link;
 friend class sll<T>;
};
template <class T>
class sll
{
 private:
  node<T> * first;
 public:
 //Mem.Fun declarations
  sll();

  int isempty();

  int length();
  T find(int i);
  node<T>* search(T x);
  void append(node<T> *k);
  void create();

};
//Member Functions defination
template<class T>
sll<T>::sll()
{
 first=NULL;//first points to no where,it is an empty node
}
template<class T>
int sll<T>::isempty()
{
 return(first==NULL);//return true when linked list is empty and false otherwise
}
//length() defination
template<class T>
int sll<T>::length()
{
 node<T> *p=first;
 int ctr=0;
 while(p!=NULL)
 {
  ctr++;
  p=p->link;
 }
 return(ctr);
}//end of length()

/*finding the value of particular node */
template<class T>
T sll<T>::find(int i)
{
 node<T> *p;
 if(i<1||i>length())
  return(-1);
 else//optional
 p=first;
 for(int j=1;j<=i-1;j++)
  p=p->link;
 return(p->data);

}

template<class T>
void sll<T>::append(node<T> *k)
{
 node<T> *last;
 k->link=NULL;
 if(isempty())
  first=k;
 else
 {
  last=first;
  while(last->link!=NULL)//keep moving last pointer until last node is reached
  {
   last=last->link;
  }
  last->link=k;//attach last node and new node k
 }
}
template <class T>
void sll<T>::create()
{
 T x;
 node<T> *k;
 first=NULL;
 cout<<"enter values terminated by -1 or !\n";
 cin>>x;
 while(x!=-1&&x!='!')
 {
  k=new node<T>;
  k->data=x;
  append(k);
  cin>>x;
 }
}//end of create()

void main()
{
 sll<int> a;//creating object a,and d.c is called
 node<int> *p;
 int x,i;
 clrscr();
 a.create();

 //find the ith node value
 cout<<"enter the which node value u want to search\n";
 cin>>i;
 x= a.find(i);
 if(x==-1)
   cout<<"Non-existing node\n";
 else
  cout<<"Data of desired node is\t"<<x<<"\n";

 getch();
}

Types of Linked list
2. Dobule Linked List
3. Circular Linked List
 

1 comment:

  1. Merkur Gold Strike Safety Razor - FEBCASINO
    Merkur's Gold Strike poormansguidetocasinogambling Safety Razor, Merkur Platinum Edge Plated Finish, German, 1xbet app Gold-Plated, หาเงินออนไลน์ Satin Chrome Finish. Merkur https://vannienailor4166blog.blogspot.com/ has a more aggressive https://febcasino.com/review/merit-casino/ looking,

    ReplyDelete