//مارتينا سامح شهدى سند
#include <iostream>
using namespace std;
typedef int ElementType;
struct node {
ElementType element;
node* next;
node* prev;
};
typedef node* Position;
class List {
private:
Position head;
Position tail;
int counter;
public:
List() {
MakeNull();
}
void MakeNull() {
head = new node;
head->next = NULL;
head->prev = NULL;
tail = NULL;
counter = 0;
}
Position End() {
Position q=head;
while (q->next != NULL)
q = q->next;
return q;
}
void Insert(ElementType x, Position pos) {
if (pos == NULL)
pos = End();
Position temp = new node;
temp->element = x;
temp->next = pos->next;
temp->prev = pos;
if (pos->next != NULL)
pos->next->prev = temp;
pos->next = temp;
if (temp->next == NULL)
tail = temp;
counter++;
}
void InsertBack(ElementType x) {
Position p = End();
Insert(x, p);
}
void Delete(Position p) {
if (p == End() || p == NULL) {
cout << "No element to delete" << endl;
}
Position temp = p->next;
if (temp == NULL) {
cout << "Invalid position!" << endl;
}
p->next = p->next->next;
if (temp->next != NULL)
temp->next->prev = p;
else
tail = p;
delete temp;
counter--;
}
Position Locate(ElementType x) {
Position p = head;
while (p->next != NULL) {
if (p->next->element == x)
return p;
p = p->next;
}
return p;
}
ElementType Retrieve(Position pos) {
if (pos == NULL || pos->next == NULL) {
cout << "ERROR in retrieve" << endl;
return NULL;
}
return pos->next->element;
}
void PrintList() {
cout << "List is ";
Position q = head->next;
while (q != NULL) {
cout << q->element << " ";
q = q->next;
}
cout << endl;
}
Position First() {
return head;
}
Position Next(Position pos) {
if (pos == tail)
return NULL;
return pos->next;
}
Position Previous(Position pos) {
if (pos == head)
return NULL;
return pos->prev;
}
int Size() {
return counter;
}
};
void reverse(List &l)
{
cout << "reverse is"<<endl;
Position q = l.End();
while (q != l.First())
{
cout << q->element <<" ";
q = l.Previous(q);
}
}
void Purge(List& l) {
Position p = l.First();
Position q = l.Next(l.First());
while (l.Next(p) != NULL) {
while (l.Next(q) != NULL) {
if (l.Retrieve(p) == l.Retrieve(q))
l.Delete(q);
else
q = l.Next(q);
}
p = l.Next(p);
}
}
int main() {
List l;
l.InsertBack(10);
l.InsertBack(20);
l.InsertBack(30);
l.InsertBack(40);
l.InsertBack(10);
l.PrintList();
cout << "After removing duplicates: " << endl;
Purge(l);
l.PrintList();
reverse(l);
return 0;
}