Problem with lists, eliminating duplicates
Hello guys! I need a bit of an advice with lists. Basically, i generated a list and created a function that should delete any duplicate information.
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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
|
#include <iostream>
using namespace std;
typedef struct nod{
int info;
nod *next;
}NOD, *PNOD;
PNOD add(PNOD head, int info_new)
{
if (head == NULL)
{
PNOD p = new NOD;
if (!p)
{
cout << "Memory was not allocated" << endl;
return NULL;
}
p->info = info_new;
p->next = NULL;
return p;
}
PNOD p = head;
while (p->next != NULL)
p = p->next;
PNOD e = new NOD;
e->info = info_new;
e->next = NULL;
p->next = e;
return head;
}
PNOD create(int n, int *v)
{
PNOD p = NULL;
for (int i = 0; i < n; i++)
p = add(p, v[i]);
return p;
}
void print(PNOD head)
{
PNOD p = head;
while (p)
{
cout << p->info << " ";
p = p->next;
}
cout << endl;
}
PNOD del_nod(PNOD head, int info_old)
{
PNOD p = head;
while (p->next->info != info_old)
p = p->next;
PNOD s = p->next;
p->next = s->next;
delete s;
return head;
}
void del_duplicates(PNOD head)
{
PNOD p = head;
while (p)
{
PNOD x = p;
while (x->next->next!=NULL)
{
x = x->next;
if (p->info == x->info) del_nod(p, x->info);
}
p = p->next;
}
}
int main()
{
PNOD head = NULL;
int dim;
int *v;
cout << "List size : "; cin >> dim;
cout << endl;
v = new int[dim];
for (int i = 0; i < dim; i++)
{
cout << "v[" << i << "]= ";
cin >> v[i];
}
head = create(dim, v);
print(head);
del_duplicates(head);
print(head);
system("PAUSE");
return 0;
}
|
Problem is, i get an unhandled exception when i hit the del_duplicates function, and i'm not quite sure why that is. Any suggestions?
Last edited on
Topic archived. No new replies allowed.