Deleting from a Linked List

I'm trying to delete a node from a linked list by a position that is passed in by a parameter. Here's my code:


void NumberList::deleteByPosition(int pos)

{
ListNode *nodePtr;
ListNode *nextNode;
ListNode *previousNode;

if(pos > numberOfNodes())
return;

for(int i = 0; i < pos; ++i) // to iterate to the position
{
deleteNode(pos);
}
}



Obviously I have another deleteNode function that i'm calling when the for loop gets to position in the list, but it doesn't work and I can't figure out why...



Here's my deleteNode function:


void NumberList::deleteNode(double num)
{
ListNode *nodePtr; // To traverse the list
ListNode *previousNode; // To point to the previous node

// If the list is empty, do nothing.
if (!head)
return;

// Determine if the first node is the one.
if (head->value == num)
{
nodePtr = head->next;
delete head;
head = nodePtr;
}
else
{
// Initialize nodePtr to head of list
nodePtr = head;

// Skip all nodes whose value member is
// not equal to num.
while (nodePtr != NULL && nodePtr->value != num)
{
previousNode = nodePtr;
nodePtr = nodePtr->next;
}

// If nodePtr is not at the end of the list,
// link the previous node to the node after
// nodePtr, then delete nodePtr.
if (nodePtr)
{
previousNode->next = nodePtr->next;
delete nodePtr;
}
}
}


EDIT***************************

that above code doesn't work at all...

i'm still having trouble with the deleting by position..

here's my new code...

void NumberList::deleteByPosition(int pos)

{
ListNode *nodePtr;
ListNode *nextNode;
ListNode *previousNode;

if(pos > numberOfNodes())
return;

for(int i = 0; i < pos; i++)
{

// Save a pointer to the next node.
nextNode = nodePtr->next;

// Delete the current node.
delete nodePtr;

// Position nodePtr at the next node.
nodePtr = nextNode;

}
}



but this doesn't work either...

Last edited on
closed account (S6k9GNh0)
Don't have much time but I have a question:
1
2
3
4
for(int i = 0; i < pos; ++i) // to iterate to the position
{
   deleteNode(pos);
}


Why is the for loop needed? The iterating variable, i, is never even used. Also, you would call the the function with the same argument multiple times. Mistake?

1
2
3
4
  deleteNode(pos); //All that's needed...
  //or
  for (i=0; i < pos; ++i)
    deleteNode(i);
the pos variable is where in the list I want the node to be deleted. such as, if pos = 0, then the first node in the list gets deleted. So the for loop just loops up to that position in the list.
Topic archived. No new replies allowed.