Cod sursa(job #1419688)

Utilizator razvan3895Razvan-Mihai Chitu razvan3895 Data 16 aprilie 2015 10:19:09
Problema Schi Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.21 kb
#include <iostream>
#include <stdio.h>
using namespace std;

template <typename T>
struct Node {
	T info;
	Node *next, *prev;
	Node() {
		next = NULL;
		prev = NULL;
	}
};

template <typename T>
class MyList {

template <typename X>
friend std::ostream& operator<<(std::ostream& out, const MyList<X>& list);

private:
	Node<T> *first;
	Node<T> *last;
	int count;

public:
	MyList() {
		count = 0;
	}

	~MyList() {
		Node<T> *crt, *next;
		crt = first;
		while(count) {
			--count;
			next = crt->next;
			delete crt;
			crt = next;
		}

	}

	bool isEmpty() {
		return count == 0;
	}

	int length() {
		return count;
	}

	void push_back(T elem) {
		Node<T> *t = new Node<T>;
		t->info = elem;
		if(isEmpty()) {
			first = t;
			first->next = t;
			last = t;
			last->prev = t;
		}
		else{
			t->prev = last;
			last->next = t;
			last = t;
			first->prev = NULL;
		}
		++count;
	}

	void push_front(T elem) {
		Node<T> *t = new Node<T>;
		t->info = elem;
		if(isEmpty()) {
			first = t;
			last = first;
			first->next = last;
			last->prev = first;
		}
		else{
			t->next = first;
			first->prev = t;
			first = t;
			last->next = NULL;
		}
		++count;
	}

	void insert(T elem, int index = 0) {
		if(index >= count - 1)
			push_back(elem);
		else if(index < 0)
			push_front(elem);
		else if(isEmpty())
			push_back(elem);
		else {
			if(index < count / 2) {
				Node<T> *t = new Node<T>, *crt = first;
				t->info = elem;
				for(int i = 0; i < index; ++i)
					crt = crt->next;
				t->next = crt->next;
				t->prev = crt;
				crt->next = t;
				++count;
			}
			else {
				Node<T> *t = new Node<T>, *crt = last;
				t->info = elem;
				for(int i = count; i > count - index; --i)
					crt = crt->prev;
				t->next = crt->next;
				t->prev = crt;
				crt->next = t;
				++count;
			}
		}		
	}
};

template <typename T>
std::ostream& operator<<(std::ostream& out, const MyList<T>& list) {
	Node<T> *crt;
	if(list.count) {
		for(crt = list.first; crt != NULL; crt = crt->next)
			out << crt->info << '\n';
	}
	return out;
}

int main() {
	MyList<int> list;
	int n, poz;
	freopen("schi.in", "r", stdin);
	freopen("schi.out", "w", stdout);
	scanf("%d", &n);
	for(int i = 1; i <= n; ++i) {
		scanf("%d", &poz);
		list.insert(i, poz - 2);
	}
	cout << list;

	return 0;
}