we just started studying about linked lists
and i wrote a simple code to build up a link list.
than post the sum of all the numbers inside the list
my problem is that i need to delete all even numbers
and i cant figure out what is wrong with the code i wrote.
its going in an inifinite loop inside the display function
[2}
(the reason for temp is to save the head pointer to first node
any other way of doing so instead of declaring new temp node for it?)]
void delete_pairs(struct Node *&head)
{
struct Node *temp,*step ;
if (head==NULL)
return;
while(head!=NULL && head->_data%2==0)
{
temp = head ;
head = head -> _next ;
delete temp ;
}
step=head;
while (step!=NULL)
{
if (step-> _data %2==0)
{
temp = step ;
step = step -> _next ;
delete temp ;
}
else
step = step -> _next ;
}
}
rest of the program (because maybe something just went on the dark side there):
/////////////
#include <iostream>
#include <cstdlib>
#include <fstream>
///////////////////
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
//////////////////
struct Node
{
int _data ;
struct Node *_next ;
};
/////////////////////////
void display_list_sum(struct Node *head);
void read_list(struct Node *&head);
void delete_pairs(struct Node *&head);
//////////////////
int main()
{
struct Node *head=NULL;
read_list(head);
display_list_sum(head);
delete_pairs(head);
display_list_sum(head);
}
//////////////////////////////////////
void display_list_sum(struct Node *head)
{
int sum=0;
struct Node *temp;
temp=head;
while (temp != NULL)
{
sum+= temp-> _data ;
temp = temp-> _next ;
}
cout<< sum<< endl;
}
///////////////////
void read_list(struct Node *&head)
{
struct Node *temp;
int num;
cin >> num ;
while (num!=0)
{
temp = new (std::nothrow) struct Node ;
if (temp == NULL)
exit(EXIT_FAILURE);
temp -> _data = num ;
temp -> _next = head ;
head = temp ;
cin >> num ;
}
}