I need to insert a node into a sorted link list, but I'm getting errors. Can someone help with what's wrong?
struct NodeType
{
ItemType value;
NodeType * next;
}
void sortedInsert( NodeType * & head, int data )
{
NodeType * p = head;
NodeType * prev = NULL;
while (p->value < data)
{
prev = p;
p= p -> next;
}
NodeType * newnode = new NodeType;
newnode -> value = data;
newnode -> next = prev;
p -> next = newnode ;
I changed the program below but I'm getting an Thread 1: EXC_BAD_ACCESS (code=1, address=0x8) error on the line prev -> next = newnode, how can I change that line?
void sortedInsert( NodeType * & head, int data ){
NodeType * p = head;
NodeType * prev = NULL;
while (p->value < data)
{
prev = p;
p= p -> next;
}
NodeType * newnode = new NodeType;
newnode -> value = data;
newnode -> next = p;
prev -> next = newnode;
if(head== nullptr)
{
NodeType * newnode = new NodeType;
newnode -> value = data;
newnode -> next = head;
return;
}
}
while (p->value < data)ifheadis null.headnode itself needs to be replaced.pandprevafter the loop. Try choosing better identifier names. Draw 3 boxes on a piece of paper, write a value inside each box, and label the boxesprev,newnode, andp. Then connect them with arrows. Now look at your code and check it's doing what your drawing says it should do.if(head== nullptr) { head = new NodeType { data, head }; return; }. If there is nohead, the new node has nowhere else but theheadto go.