#include
struct Link
{
int data;
Link *next;
};
class Linklist
{
private:
Link *first;
public:
Linklist() {first = NULL;}
void AddOrder(int d);
void AddToFront (int d);
void AddToEnd(int d);
void display ();
void FindAndKill (int d);
int Search(int d);
};
// adds an element in order
void Linklist::AddOrder(int d)
{
Link *current = first;
Link *last= current;
Link *newLink = new Link;
newLink->data = d;
newLink->next = NULL;
if (current == NULL)
{
first = newLink;
return;
}
else
{
while (current != NULL)
{
if (current->data > d && last == current)
{
newLink->next = current;
first = newLink;
return;
}
else if (current->data > d && last != current)
{
last->next= newLink;
newLink->next = current;
return;
}
else if (current->data == d)
return; /////can be changed!!
else if (current->data < d && current->next == NULL)
{
current->next = newLink;
return;
}
else
{
last= current;
current = current->next;
}
}
}
}
// deletes element with value d from lis
// t
void Linklist::FindAndKill(int d)
{
Link *current = first;
Link *last= current;
if (current == NULL)
return;
else if (current->next == NULL && current->data ==d )
{
first = NULL;
return;
}
else
{
while (current != NULL)
{
if (current->data == d && current==first)
first= current->next;
else if (current->data ==d && current !=first)
last->next=current->next;
else
last = current;
current = current->next;
}
}
}
//searches for an element and returns 1
// if it exists, otherwise 0
int Linklist::Search(int d)
{
Link *current = first;
while (current != NULL)
{
if (current->data == d)
return 1;
current = current->next;
}
return 0;
}
// adds an element to front of linked li
// st
void Linklist::AddToFront (int d)
{
Link *newLink = new Link;
newLink->data = d;
newLink->next = first;
first = newLink;
}
// adds an element to end of linked list
//
void Linklist::AddToEnd (int d)
{
Link *current = first;
Link *newLink = new Link;
newLink->data = d;
newLink->next = NULL;
if (current == NULL)
first = newLink;
else
while (current != NULL)
{
if (current->next != NULL)
current = current->next;
else
{
current->next = newLink;
break;
}
}
}
// outputs the contents of the linked li
// st
void Linklist::display()
{
Link *current = first;
while (current != NULL)
{
cout << endl << current->data;
current = current->next;
}
}
// example of using the class
void main()
{
Linklist Li;
Li.AddOrder(7);
Li.AddOrder(1);
Li.AddOrder(6);
Li.AddOrder(-5);
Li.AddOrder(3);
Li.AddOrder(0);
Li.AddOrder(9);
if ( Li.Search ( 3 ) ) cout << "3 is in the list!\n";
Li.FindAndKill ( 6 );
Li.display();
}