hi,
in my code at the bottom, everything works perfectly except for the function to delete the pointer. i've been working on it for hours and understand the concept that the node is not "deleted" rather it's skipped. the node before the current node is linked to the next node and then the current node is deleted to save memory.
i just can't seem to get it on code. can someone help me with the delete function? the main problem i have is that...let's say i have the current node to be deleted, how do i point to the previous node and the next node?
i thought about searching for the node and then having a separate function to delete the node. or iterate through the node and do the linking in there and that's where i get lost with the previous/next node.
thanks,
barneygumble742
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
struct car_node
{
string make;
int year;
car_node *next;
};
typedef car_node* car_node_pointer;
void head_insert(car_node_pointer &head, string temp_make, int temp_year);
void add(car_node_pointer after_me, string temp_make, int temp_year);
void print(car_node_pointer &temp);
void print_all(car_node_pointer &head);
car_node_pointer search(car_node_pointer &head, string temp_make);
void askuser(string &make, int &year);
void delete_node(car_node_pointer &head, string temp_make);
int main()
{
string make, space; int year=0; ifstream fin("cars1.txt"); ofstream fout("cars2.txt");
car_node_pointer head = new car_node;
car_node_pointer after_me = new car_node;
car_node_pointer temp1 = new car_node;
after_me->next = head;
head->next=NULL;
while(!fin.eof())
{
getline(fin, make);
fin >> year;
getline(fin, space);
add(head, make, year);
}
print_all(head);
askuser(make, year);
delete_node(head, make);
print_all(head);
return 0;
}
car_node_pointer search(car_node_pointer &head, string temp_make)
{
car_node_pointer here = head;
if(here == NULL)
{
return NULL;
}
else
{
while(here->make != temp_make && here->next != NULL)
here = here->next;
if(here->make == temp_make)
return here;
else
return NULL;
}
}
void delete_node(car_node_pointer &head, string temp_make)
{
car_node_pointer current = new car_node;
if(head->make == temp_make)
{
current = head;
head = head->next;
}
else
{
current = head;
while(current->make = temp_make)
{
current->next = head;
}
if(current->make = temp_make)
{
car_node_pointer discard = current;
current->next = discard->next;
delete discard;
}
}
}