Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
2.9 kB
1
Indexable
Never
#include <iostream>
using namespace std;

struct elem
{
	int key;
	elem *prev;
	elem *next;
};

void add_start(int n, elem*&start)
{
	elem * p = start;
	start = new elem;
	start ->key = n;
	start ->next = p;
	start ->prev = NULL;
	if (p) p ->prev = start;
}

void add_end(int n, elem*&start)
{
	elem* q = new elem;
	q-> key = n;
	q ->next = NULL;
	if(start != NULL)
	{
		elem* p = start;
		while(p -> next != NULL)
		{
			p = p -> next;
		}
		p -> next = q;
		q -> prev = p;
	}
	else
	{
		q ->prev = NULL;
		start = q;
	}
}

bool del_n(int &n, elem*&start)
{
	if (start != NULL)
	{
		elem*p = start;
		while (p->key !=n && p->next != NULL)
		{
			p = p ->next;
		}
		if (p->key == n)
		{
			if (p->prev != NULL)
			{
				(p->prev)->next = p->next;
			}
			else start = p->next;
			if (p->next != NULL)
			{
				(p->next)->prev = p->prev;
			}
			delete p;
			p = NULL;
			return true;
		}
		return false;
	}
	else return false;
}

bool kratni(int n, elem*&start)
{
	if (start != NULL)
	{
		elem*p = start;
		while (p->key % n !=0 && p->next != NULL)
		{
			p = p ->next;
		}
		if (p->key % n == 0)
		{
			if (p->prev != NULL)
			{
				(p->prev)->next = p->next;
			}
			else start = p->next;
			if (p->next != NULL)
			{
				(p->next)->prev = p->prev;
			}
			delete p;
			p = NULL;
			return true;
		}
		return false;
	}
	else return false;
}

void change_nums(elem*& start, int i, int k)
{
	if(start != NULL)
	{
		elem* p = start;
		elem * q = start;
		while (p -> key != i && p->next != NULL)
		{
			p = p->next;
		}
		while (q -> key != k && q->next != NULL)
		{
			q = q->next;
		}
		if (p ->key != i && q->key != k)
		{
			cout << "Couldn't find one of the numbers!" << endl;
			return;
		}
		else
		{
			elem* temp = p;	
			p ->prev = q ->prev;
			p -> next = q -> next;
			(q->prev) -> next = p;
			(q->next) -> prev = p;
			q -> prev = temp -> prev;
			q -> next = temp -> next;
			(temp->prev) -> next = q;
			(temp->next) -> prev = q;
			delete temp;
			temp = NULL;
		}
	}
	else
	{
		cout << "List is empty" << endl;
	}
}

void print_list(elem* &start)
{
	elem * p = start;
	cout << "List: ";
	while (p)
	{
		cout << p ->key << " ";
		p = p -> next;
	}
}

int main()
{
	elem * start = NULL;
	int ch;
	do
	{
		cin >> ch;
		switch (ch)
		{
		case 1:
		case 2:
			int num;
			cout << endl <<"Insert num: "<< endl;
			cin >> num;
			if(ch == 1) add_start(num, start);
			else add_end(num, start);
			break;
		case 3:
			cout << endl << "Predi:" << endl;
			print_list(start);
			cout  << endl<< "Sled:" << endl;
			//int kr = 2;
			//while(kratni(kr, start));
			print_list(start);
			system("pause");
		case 4:
			int i,k;
			cin >> i;
			cin >> k;
			change_nums(start, i, k);
			break;
		}
	} while (ch != 0);
}