I know something about pointers, but I'm trying to check my knowledge on a sample. Can somebody check if my code is good? I don't think that I should use pointers in these struct
s.
The second question is: Can I use a for
loop like this?
for(DLList* i=first; i!=0; i=i->next)
Is it correct?
struct Node
{
int id;
int dist;
Node* prev;
vector<Edge*> edges;
};
struct Edge
{
int length;
Node* to;
};
struct DLList
{
DLList *next;
DLList *prev;
Node* val;
};
struct DList
{
DLList *first,*last;
DList()
{
first = 0;
last = 0;
}
DLList* add(Node* n)
{
DLList *newNode = new DLList;
if(first == 0)
{
newNode->val = n;
newNode->next = 0;
newNode->prev=0;
first = newNode;
last = newNode;
}
else
{
newNode->val = n;
newNode->next = 0;
newNode->prev=last;
last = newNode;
last->next=newNode;
}
return last;
}
void removeFirst()
{
if(first!=0)
{
first = first->next;
if(first != 0)
{
first->prev = 0;
}
}
}
void remove(DLList* e)
{
if(e==0)
{
return;
}
else if(e==first)
{
removeFirst();
}
else if(e==last)
{
last = last->prev;
last -> next = 0;
}
else
{
e->prev->next = e->next;
e->next->prev = e->prev;
}
}
void remove(Node* n)
{
if(first == 0)
{
return;
}
if(n==first->val)
{
removeFirst();
}
else if(n==last->val)
{
last = last->prev;
last->next = 0;
}
else
{
for(DLList* i=first; i!=0; i=i->next)
{
if(n==i->val)
{
i->prev->next = i->next;
i->next->prev = i->prev;
break;
}
}
}
}
bool isEmpty()
{
return first == 0;
}
};
0
to indicate a null element, usenullptr
. \$\endgroup\$