nullPointer2
nullPointer2

Reputation: 87

adding elements to sorted linked lists

I'm working on single linked lists in which I got a problem with add function which adds integers into sorted way. But my program keeps crashing. I've been working all the night but I couldn't find the problem. Does anyone has any idea about this?

Thank you

template<typename T>
class SLList
{
private:

struct Node
{

Node(const T& val= T(), Node* next_ptr=NULL) : data(val), next(next_ptr) { }

// data members
T data;
Node *next;
};


 template<typename T>

void SLList<T>::add(const T& val)
{
 if (find(val)==false)
  {
 Node *curr= head;
 Node* prev=NULL;
  if(head->next==NULL)
  {
      cout<<"head";
      Node *tmp=new Node(val,head->next);
      head->next=tmp;
      return;
  }
  else
  {
  while(curr->data < val && curr!=NULL)
  {
      curr=curr->next;
      prev=curr;
      cout<<"add";
  }

Node *tmp=new Node(val, prev->next);
//head->next=tmp;
  }
}
}    `

Upvotes: 0

Views: 495

Answers (2)

Igor F.
Igor F.

Reputation: 2699

Also, move prev = curr forward:

while(curr != NULL && curr->data < val) {
  prev = curr;
  curr = curr->next;
  cout << "add";
}

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258618

The while exit condition is inverted:

while(curr->data < val && curr!=NULL)

should be

while( curr!=NULL && curr->data < val )

If curr is NULL, it will crash (well, UB to be exact) before it checks for NULL.

Upvotes: 1

Related Questions