data structures question
Write a program to copy the content of array to a dynamic single linked list and write a function to delete every node has an even value in its data
this is my program, but didnt work with me
plz tell me where is my wrong ??
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
|
#include <iostream>
using namespace std;
struct list
{
int data;
list *next;
};
void del_Ev(list *&head, list *&tail)
{
list *ptr = head ;
while(ptr)
{
if(tail->data % 2 == 0)
{
if(tail == head)
{ list *node = tail ;
head = head->next ;
delete node;
tail = tail->next ;
}
else
{
list *node = tail ;
tail = tail->next ;
delete node;
}
}
else
{
tail = tail->next ;
}
ptr = ptr->next ;
}
}
int main() {
list *node = NULL, *tail = NULL, *head = NULL;
int a[] = {1, 4, 6, 3, 7, 11, 8, 9, 10};
for (int i = 0; i < 9; i++)
{
node = new list; // create new node ...
node->data = a[i]; //set a[i] value to date element in newnode structure
node->next = NULL; //set next to null to be end of node ...
if (head == NULL) {
head = node;
tail = node; //set tail to piont to end of list ..
}
else
{
tail->next = node;
tail = node;
}
}
tail = head ;
// after deleting %2 = 0;
del_Ev(head, tail);
list *tmp = new list;
tmp = head;
while (tmp) {
cout << tmp->data << " ";
tmp = tmp->next;
}
return 0;
}
|
What was the problem? What errors were you getting? Did you try debugging it?
Your code is a little messy and misleading. Please use structures to manage the head and tail. Here's a more proper format.
1 2 3 4 5 6 7 8 9 10 11 12
|
template<typename T>
struct list
{
struct node
{
T data;
node *next;
};
node *head;
node *tail;
};
|
and provide functions to manage them such. I will promise you it will be easier this way. Remember your rule of 3 as well.
Topic archived. No new replies allowed.