List Data Structure Using Singly Linked List In Data Structure Using C++

Data Structure Using C++

List Data Structure

List Using Singly Linked List

class node
{
 private:
  int data;
  node *next;
 public:
  node(int d);
  void set(int d);
  int get ();
  void setNext (node *);
  node* getNext();
  void showData();
};
node::node(int d)
{
 data=d;
 next=NULL;
}
void node::set(int d)
{
 data=d;
}
int node::get()
{
 return data;
}
void node::setNext(node* n)
{
 next=n;
}
node* node::getNext()
{
 return next;
}
void node::showData()
{
 cout<<get()<<"\t";
}

class LinkedList{
 private:
  node* headNode;
  node* currentNode;
  int size;
 public:
  LinkedList();
  void start();
  void next();
  int get();
  int length();
  void add(int d);
  void update(int d);
  void remove();
  void find(int d);
  void showList();
};
LinkedList::LinkedList(){
 headNode=NULL;
 currentNode=NULL;
 size=0;
}
void LinkedList::start(){
 currentNode=headNode; 
}
void LinkedList::next(){
 if(currentNode->getNext()!=NULL){
  currentNode=currentNode->getNext();
 }
}
int LinkedList::get(){
 if(currentNode!=NULL){
  return currentNode->get();
 }
}
int LinkedList::length() 
{  
 return size;  
}
void LinkedList::add(int d) 
{ 
    node* newNode=new node(d); 
    if(size==0){
     currentNode=newNode;
     headNode=newNode;
 }
 else{
        newNode->setNext(currentNode->getNext());
        currentNode->setNext(newNode);
        currentNode = newNode;
 }
    size ++;
}
void LinkedList::update(int d){
 if(currentNode!=NULL){
  currentNode->set(d);
 }
}
void LinkedList::remove() {
 if(currentNode!=NULL && currentNode!=headNode){
  node* ptr;
  ptr=headNode;
  while(ptr->getNext()!=currentNode){
   ptr=ptr->getNext();
   break;
  }
  ptr->setNext(currentNode->getNext());
  currentNode=ptr;
  size--; 
 }
 else if(currentNode==headNode){
  currentNode=currentNode->getNext();
  headNode=currentNode;  
  size--;
 }else{
  cout<<"List is empty";
 }
}
void LinkedList::find(int d){
 node* ptr;
 ptr=headNode;
 do{
  if(ptr->get()==d)
  {
   cout<<"Value is found"<<endl;
  }
  else
  {
   cout<<"Value is not found!"<<endl;
  }
  ptr=ptr->getNext();
 }while(ptr!=NULL);
 
}
void LinkedList::showList(){
 node* ptr;
 ptr=headNode;
 do{
  ptr->showData();
  ptr=ptr->getNext();
 }while(ptr!=NULL);
 cout<<endl;
}
int main(){
 LinkedList list;  
 list.add(5);
 list.add(7);
 list.showList();
 list.remove();
 list.update(3);
 list.showList();
 list.start();
 list.add(9);
 list.showList();
 list.start();
 list.remove();
 list.showList();
 list.find(9);
 list.update(3);
 list.showList();
}

Let me know in the comment section if you have any question.

Previous Post:
List Data Structure Using Array In Data Structure Using C++


Comments