-
Deleting nodes
Ok, I have been fooling around with linked lists, and so far I feel that I have been mastering it pretty good. Hpwever, when it comes to deleting nodes off the list, I am not succeeding!! Here is the following code that is obviously logically erronous.
Code:
do
{
cout << "enter a digit to delete from the list: ";
cin >> v;
active = first;
while ( active->next != NULL)
{
if(active->next->key == v)
{
active->next = active->next;
active->next = active->next->next;
delete active;
}
else
active = active->next;
}
/*Print the list out after removing the node */
active = first;
do
{
if (active->next != NULL)
cout << active->key << " ";
active = active->next;
}while(active != NULL);
cout << endl;
}while(first->next != NULL);
It seems to me like that should do the trick. For ease, below I'll just post my main deletion method, if it in itself is the problem:
Code:
active->next = active->next;
active->next = active->next->next;
delete active;
The results have been quite odd.
-
First off, why do you do this:
Code:
active->next = active->next;
All you are doing is setting it equal to itself which doesn't do anything. Second, you want to make sure you delete active->next since that is the node you want deleted, not active.
-
Well, I must admit, I whipped that up a bit quick. Here is my newly completed code, which I am trying to emulate a stack with (notice the driver program isnt extravagant yet)
Code:
#include <iostream.h>
#include <stdlib.h>
struct node
{ int key; struct node *next;};
typedef node* stack_ptr;
void push(stack_ptr& a_stack, int number);
void print_list(stack_ptr& a_stack, stack_ptr& b_stack);
void pop(stack_ptr& a_stack,stack_ptr& b_stack);
main()
{
int n, v;
struct node *t, *x;
/* initialize the list */
t = new node;
t->next = NULL;
x = t;
cout << " How many numbers in the list? ";
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "Enter a number to add to the list: ";
cin >> v;
push(t, v);
}
print_list(t,x);
pop(t, x);
return 0;
}
void push(stack_ptr& a_stack, int number)
{
a_stack->next = new node;
a_stack->next->next = NULL;
a_stack->key = number;
a_stack = a_stack->next;
}
void print_list(stack_ptr& a_stack, stack_ptr& b_stack)
{
a_stack = b_stack;
do
{
if (a_stack->next != NULL)
cout << a_stack->key << " ";
a_stack = a_stack->next;
}while(a_stack != NULL);
cout << endl;
}
void pop(stack_ptr& a_stack,stack_ptr& b_stack)
{
a_stack = b_stack->next;
while(a_stack->next->next != NULL)
a_stack = a_stack->next;
delete a_stack->next;
a_stack->next = NULL;
}
Please... tell me if there is any inefficiency here! :D