Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- ifstream in("input.txt");
- ofstream out("output.txt");
- template <class Item>
- class DoubleLinkedList
- {
- struct Element
- {
- Item inf;
- Element *next;
- Element *prev;
- Element (Item x): inf(x), next(0), prev(0)
- {
- }
- };
- Element *head;
- Element *tail;
- int size;
- Element *Find(int index)
- {
- if(index < 0 || index > size)
- return NULL;
- else
- {
- Element *cur = head;
- int i = 0;
- while (i < index)
- {
- if (cur->next == NULL) break;
- i++;
- cur = cur->next;
- }
- return cur;
- }
- }
- public:
- DoubleLinkedList():head(0), tail(0), size(0) {}
- ~DoubleLinkedList()
- {
- while(!Empty())
- Remove(0);
- }
- bool Empty()
- {
- return head == 0;
- }
- int GetLength()
- {
- return size;
- }
- Item Get(int index)
- {
- if (index < 0 || index > size)
- {
- cout << "Error";
- }
- else
- {
- Element *r = Find(index);
- Item i = r->inf;
- return i;
- }
- return 0;
- }
- void InsertHead(Item data, int index)
- {
- if (index < 0 || index > size)
- {
- cout << "Bug";
- }
- else
- {
- Element *newPtr = new Element(data);
- size = GetLength() + 1;
- Element *cur = Find(index-1);
- if (cur == NULL)
- {
- head = newPtr;
- tail = newPtr;
- }
- else
- {
- newPtr->next = cur;
- newPtr->prev = cur->prev;
- cur->prev = newPtr;
- if(cur == head)
- head = newPtr;
- else newPtr->prev->next = newPtr;
- }
- }
- }
- void InsertTail(Item data, int index)
- {
- if ((index < 0 && head != NULL) || (index > size))
- {
- cout << "Bug";
- }
- else
- {
- Element *newPtr = new Element(data);
- size = GetLength() + 1;
- Element *cur = Find(index-1);
- if (cur == NULL)
- {
- head = newPtr;
- tail = newPtr;
- }
- else
- {
- newPtr->next = cur->next;
- newPtr->prev = cur;
- cur->next = newPtr;
- if(cur == tail)
- {
- tail = newPtr;
- }
- else
- newPtr->next->prev = newPtr;
- }
- }
- }
- void Remove (int index)
- {
- if (index < 0 || index > size)
- {
- cout << "Error";
- }
- else
- {
- Element *cur = Find(index);
- size--;
- if (size == 0)
- {
- head = NULL;
- tail = NULL;
- }
- else if (cur == head)
- {
- head = head->next;
- head->prev = NULL;
- }
- else if (cur == tail)
- {
- tail = tail->prev;
- tail->next = NULL;
- }
- else
- {
- cur->prev->next = cur->next;
- cur->next->prev = cur->prev;
- }
- cur->next = NULL;
- cur->prev = NULL;
- delete cur;
- }
- }
- void Print(ofstream &out)
- {
- for(Element * cur = head; cur != NULL; cur = cur->next)
- out << cur->inf << " ";
- out << endl;
- }
- };
- int main (void)
- {
- DoubleLinkedList <int> l;
- int i;
- while (in >> i)
- {
- l.InsertTail(i, l.GetLength());
- }
- int k = l.GetLength();
- for (int i = 0; i < k; i++)
- {
- if (l.Get(i) % 2 == 0)
- {
- l.InsertTail(l.Get(i), i);
- k++;
- i++;
- }
- }
- l.Print(out);
- }
Advertisement
Add Comment
Please, Sign In to add comment