I needed help with adding a node part in my doubly linked list. I've dry run my program it seems perfect yet it crashes on adding the second or third node. I want a logical reason why is it so. Anyone? Here's my code.
class node
{
public:
int data;
node* next;
node* previous;
};
class linklist
{
private:
node* current;
node* head;
node* tail;
int count;
int size;
public:
linklist() : head(NULL), tail(NULL), size(1) {}
void addNthNode(int Data, unsigned int position)
{
node* currentNew = new node;
currentNew->data = Data;
if (position == 1)
{
currentNew->next = head;
currentNew->previous = NULL;
head = currentNew;
return;
}
node* temp1 = head;
for (int i = 1; i < position - 1; i++)
temp1 = temp1->next;
node* temp2 = temp1->next;
currentNew->previous = temp1;
currentNew->next = temp2;
}
int getSizeOfList()
{
node* temp = head;
while (temp->next != NULL)
{
temp = temp->next;
++size;
}
return size;
}
void main()
{
linklist l;
l.addNthNode(1, 1);
l.addNthNode(2, 2);
l.addNthNode(3, 3);
l.printList();
cout << "\nSize of list : " << l.getSizeOfList() << endl << endl;
}
Aucun commentaire:
Enregistrer un commentaire