Практичне заняття
Приклад 1. Створення списку, роздрук та додаванняч нового елементу.
#include <iostream.h>
#include <stdlib.h>
#include <time.h>
struct TElem
{
int data;
TElem *next;
TElem *prev;
};
TElem *creat(int n)
{
TElem *head = NULL,*current,*curpr;
for(int i=0;i<n;i++)
if (!head)
{
head = new TElem();
head->data = rand()%100;
head->next = 0;
head->prev = 0;
current = head;
}
else
{
current->next = new TElem();
curpr=current;
current = current->next;
current->data = rand()%100;
current->next = 0;
current->prev=curpr;
}
return head;
}
void print(TElem *h)
{
cout<<"Spisok\n";
while(h!=0)
{
cout<<h->data<<" ";
h=h->next;
}
cout<<endl;
}
void addn(TElem *&head,int v1)
{
TElem *pr;
pr= new TElem();
pr->data=v1;
pr->prev=0;
pr->next=head;
head=pr;
}
void addk(TElem *head,int v1)
{
TElem *pr;
pr= new TElem();
pr->data=v1;
pr->next=0;
while(head!=0)
{
pr->prev= head;
if(head->next==0){head->next=pr;break;}
head=head->next;
}
}
void del(TElem *&h,int v1)
{
TElem *head=h,*pr;
while(head!=0)
{
if(head->data==v1)
{
if (head->prev==0)
{
h=head->next;
delete head;
}
else
if (head->next==0)
pr->next=0;
else
{
pr->next=head->next;
head->next->prev=head->prev;
}
break;
}
pr=head;
head=head->next;
}
if(head==0)
cout<<"not found v1 addpz"<<endl;
}
void main()
{
time_t t;
srand((unsigned) time(&t));
TElem *head,*pois ;
int n;
cout<<"Input n\n";
cin>>n;
head=creat(n);
print(head);
int v1;
int v2;
cout<< "Input value addn: ";
cin>>v1;
addn(head,v1);
print(head);
cout<< "Input value addk: ";
cin>>v1;
addk(head,v1);
print(head);
cout<< "Del Input value : ";
cin>>v1;
del(head,v1);
print(head);
cout<< "Input value poisk: ";
cin>>v1;
pois=poisk(head,v1);
if (pois!=0)
cout<<"Find value :"<<pois->data<<endl;
cout<< "values to swap: ";
cin>>v1>>v2;
obmen(head,v1,v2);
print(head);
pois=newsp(head);
print(pois);
cin.get();
}