Skip to content

Instantly share code, notes, and snippets.

@chrisdel101
Last active April 5, 2020 18:57
Show Gist options
  • Save chrisdel101/8bcb010ec1f015b345b01d5ad8851c08 to your computer and use it in GitHub Desktop.
Save chrisdel101/8bcb010ec1f015b345b01d5ad8851c08 to your computer and use it in GitHub Desktop.
2 functions
SparseArrayNode *SparseArray::getPreviousNode(int index)
{
// if null or current index is greater than head index
cout << endl;
cout << "current node INDEX " << index << endl;
if (headPtr != NULL)
{
cout << "prev node HEAD INDEX " << headPtr->index << endl;
}
cout << endl;
if (headPtr == NULL || headPtr->index >= index)
{
cout << "STOP" << endl;
return NULL;
}
// assign head to cursor
SparseArrayNode *pNode = headPtr;
// create temp store
SparseArrayNode *previous = NULL;
while (pNode != NULL)
{
// if index is greater, than previous was less
cout << "current is " << pNode->index << endl;
if (previous)
cout << "previous is" << previous->index << endl;
if (pNode->index > index)
{
cout << "HERE " << pNode->index << endl;
// cout << "previous is " << previous->index << endl;
return previous;
}
// track previous so it can be returned
previous = pNode;
// move to next node
pNode = pNode->next;
}
}
void SparseArray::insert(int index, const string &value)
{
// assert(invariant());
if (headPtr == NULL)
{
cout << "HERE" << endl;
SparseArrayNode *s = new SparseArrayNode();
s->value = value;
s->index = index;
s->next = NULL;
headPtr = s;
return;
}
if (value != default_value)
{
// check if node index exists
SparseArrayNode *existingNode = getExactNode(index);
// if it does, change the value
if (existingNode)
{
existingNode->value = value;
}
else
{
// get previous node
SparseArrayNode *previousNode = getPreviousNode(index);
cout << "prev node val " << previousNode << endl;
if (previousNode != NULL)
{
// cout << "prev node val " << previousNode->value << endl;
SparseArrayNode *s = new SparseArrayNode();
s->index = index;
s->value = value;
// point new node at what previous node pointed to
s->next = previousNode->next;
// point previous at new node
previousNode->next = s;
}
else
// if only one node, so no previous
{
SparseArrayNode *s = new SparseArrayNode();
cout << "bottom of insert here " << endl;
s->index = index;
s->value = value;
//SEG FAULT HERE
s->next = headPtr->next;
// make s new head
headPtr = s;
}
}
}
// assert(invariant());
}
int main()
{
// make array
SparseArray s;
s.insert(2, "a");
s.printNodes();
s.insert(4, "b");
s.printNodes();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment