Sunday, August 24, 2014

Linked List- Data Structure C++

// Linked_List.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class Node{
public:
int data;
Node *next;
Node *previous;

Node(){
next=NULL;
previous=NULL;
}
};

class LinkedList{
private:
Node *head;
Node *current;
Node *end;
public:
LinkedList()
{
head=NULL;
current=NULL;
end=NULL;
}
void addElement()
{
Node *temp;
temp=new Node;
cout<<"\nEnter element data: ";
cin>> temp->data;
if(head==NULL)
{
head=temp;
temp->next=NULL;
}
else
{
current=head;
while(current->next != NULL)
{
current=current->next;
}
current->next =temp;
}
}

void remove()
{
int n;
cout<<"Enter the element you want to remove: ";
cin>>n;
current=head;
Node *previous=current;
while(current->data!=n)
{
previous=current;
current =current->next;
}
Node *temp=current;
previous->next=current->next;
delete temp;
}

void countElements()
{
int count=0;
current =head;
while(current->next!=NULL)
{
current=current->next;
count++;
}
count++;
cout<<"The total number of elements are: "<<count;
}

void display(){
current=head;
cout<<"The list contains the following elements:\n";
while(current->next!=NULL)
{
cout<<current->data<<endl;
current=current->next;
}
cout<<current->data;
}
};


int _tmain(int argc, _TCHAR* argv[])
{
LinkedList a;
int option;

cout<< "Enter you choice:\n1:Add Element\n2:Remove Element\n3:Total number of elements\n4:Display List\nEnter 'e' to end\n";
cin>>option;

while(option!='e'){

switch (option){
case 1:
a.addElement();
break;
case 2:
a.remove();
break;
case 3:
a.countElements();
break;
case 4:
a.display();
break;
}
cout<< "Enter you choice:\n1:Add Element\n2:Remove Element\n3:Total number of elements\n4:Display List\nEnter 'e' to end\n";
cin>>option;
}
return 0;
}

No comments:

Post a Comment