New to linked lists, having seg fault error

So I'm new to linked lists and I keep getting a segmentation fault error. Can anyone spot my error in my insertion and deletion methods? Any explanation would be so appreciated.

Notes:
My constructor for the list creates a head node and makes its pointer point to NULL.
My carX.compare(carY) function determines which car is "better", and returns -1 if car x is "lesser"
quality, returns 0 if they have the same info, or returns 1 if carX is "better" than carY

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
 void List::insert(int price, int year, string model)
{
	if (isEmpty()==true)//if list is empty
	{
		NodePtr newNode = new Node; //create a new node
		newNode->data.setPrice(price);
	        newNode->data.setYear(year);
		newNode->data.setModel(model);
		newNode->next = NULL;
		head->next = newNode;
	}
	else//if list is NOT empty
	{
		NodePtr cur;
		cur = head->next;
		while(cur !=NULL)
		{
			if (cur->data.compare(cur->next->data)<0 && cur->next != NULL)
				cur = cur->next;
		}
		if (cur->data.compare(cur->next->data)>0)
		{
			NodePtr newNode = new Node;
			newNode->next = cur->next;
			cur->next = newNode;
			newNode->data.setPrice(price);
			newNode->data.setYear(year);
			newNode->data.setModel(model);
		}
		else if (cur->next=NULL)
		{
			NodePtr newNode = new Node;
			newNode->next = NULL;
			cur->next = newNode;
			newNode->data.setPrice(price);
			newNode->data.setYear(year);
			newNode->data.setModel(model);
		}
	}
}
void List::remove(int price, int year, string model)
{
	if(isEmpty()==true)//if list is empty
	{
		cout<< "Unable to find (and therefore remove) the car" << endl;
		return;
	}
	else //if list is NOT empty 
	{
		NodePtr cur;
		cur = head->next;
		NodePtr prev = cur;
		while(cur != NULL)
		{
			if(cur->data.compare(cur->next->data)!=0)
			{
				prev = cur;
				cur = cur->next;
			}
			else 
			{
				prev->next = cur->next;
				delete cur;
				cur = NULL;
			}
		}		
		if (cur==NULL)
			cout<< "Unable to find (and therefore remove) the car" << endl;
		
	}
}
On line 10, you try to access head->next even though your if statement is designed to execute that code only when head is nullptr. You want to assign to head instead.
Topic archived. No new replies allowed.