Witam, implementacja działa, ale mam kilka pytań odnośnie listy jednokierunkowej uporządkowanej.
1.Czy można uprościć metody, które napisałem (bez użycia STL List) czyli zmniejszyć liczbę warunków itd ?
2.Czy użycie listy dwukierunkowej pomoże w osiągnięciu celu z punktu 1 ?
#include <iostream>
using namespace std;
struct sListElem
{
int data;
sListElem* next;
};
sListElem* head = NULL;
void pushInOrder(int x)
{
sListElem* q = new sListElem;
q->data = x;
q->next = NULL;
if(head==NULL)
{
head=q;
}
else if(head!=NULL && head->data > x)
{
q->next=head;
head=q;
}
else
{
sListElem* temp = head;
while(temp->next!=NULL && temp->next->data < x)
{
temp=temp->next;
}
q->next=temp->next;
temp->next=q;
}
}
void printInOrder(void)
{
sListElem* pom = head;
unsigned int counter = 0;
while(pom!=NULL)
{
counter++;
cout<<pom->data<<endl;
pom=pom->next;
}
cout<<"numbers of elements: "<<counter;
}
void popInOrder(int x)
{
if(head!=NULL)
{
sListElem* pom2 = head;
if(head->data==x)
{
head=pom2->next;
delete pom2;
}
else
{
bool flag = false;
while (flag==false && pom2->next!=NULL)
{
if(pom2->next->data==x)
{
flag=true;
}
else
{
pom2=pom2->next;
}
}
if(flag==true)
{
sListElem* e = pom2->next;
pom2->next = e->next;
delete e;
}
else
{
cout<<"element not found "<<endl;
}
}
}
else
{
cout<<"list is empty! "<<endl;
}
}
int main(void)
{
pushInOrder(5);
pushInOrder(3);
pushInOrder(12);
pushInOrder(12);
pushInOrder(1);
pushInOrder(100);
printInOrder();
cout<<endl<<endl;
popInOrder(1);
printInOrder();
cout<<endl<<endl;
popInOrder(50);
printInOrder();
cout<<endl<<endl;
popInOrder(12);
printInOrder();
cout<<endl<<endl;
popInOrder(5);
printInOrder();
cout<<endl<<endl;
popInOrder(12);
printInOrder();
cout<<endl<<endl;
popInOrder(100);
printInOrder();
cout<<endl<<endl;
popInOrder(3);
printInOrder();
cout<<endl<<endl;
popInOrder(50);
printInOrder();
return 0;
}