Im having real trouble seeing this, how do I delete something out of a linked list if it is already there? My current delete function just deletes everything out of the list.
the text file contains numbers like this:
75
85
95
25
35
75
85
95
25
#include <iostream>
#include <fstream>
using namespace std;
class List
{
public:
void Insert(int);
void Print();
//
void Delete(int);
int Length(int);
};
struct node
{
int item;
node *nxt;
};
node *start_ptr = 0;
node *current;
void List::Delete(int item)
{
if(start_ptr==NULL)
cout<<"NULL";
node* temp=start_ptr;
if(temp->item==item)
{
start_ptr=temp->nxt;
delete temp;
}
}
void List::Insert(int item)
{
node *temp, *temp2; // Temporary pointers
// Reserve space for new node and fill it with data
temp = new node;
temp->item=item;
temp->nxt = NULL;
// Set up link to this node
if (start_ptr == NULL)
{
start_ptr = temp;
current = start_ptr;
}
else
{
temp2 = start_ptr;
while (temp2->nxt != NULL)
{
temp2 = temp2->nxt;
// Move to next link in chain
}
temp2->nxt = temp;
}
}
void List::Print()
{
node *temp;
temp = start_ptr;
if (temp == NULL)
cout << "The list is empty" << endl;
else
{ while (temp != NULL)
{ // Display details for what temp points to
cout << temp->item << " ";
if (temp == current)
cout << " <--";
cout << endl;
temp = temp->nxt;
}
cout << "End of list" << endl;
}
}
int List::Length(int item)
{
node *temp;
temp=start_ptr;
temp->item=item;
int count=0;
while(temp != 0)
{
temp=temp->nxt;
count++;
}
return count;
}
void main()
{
List display;
fstream inFile;
node number;
inFile.open("numbers.txt");
while(inFile>>number.item)
{
display.Insert(number.item);
display.Delete(number.item);
}
display.Print();
//cout<<display.Length(number.item);
}