#include "stdafx.h" using namespace std; struct list { int val; list *next; }; void print(list *a) { list *p = a; cout << "Spisok: "; while (p != NULL) { cout << p->val; p = p->next; } } list *init(int a) { list *head = new list; head->val = a; head->next = NULL; return (head); } list *add(list *head, int data) { list *temp, *p; p = head->next; temp = new list; head->next = temp; temp->val = data; temp->next = p; return (temp); } void del(list *&p, int v) { if (p == NULL) return; list *t = p; if (t->val == v) { p = t->next; delete t; return; } list *t1 = t->next; while (t1) { if (t1->val == v) { t->next = t1->next; delete t1; return; } t = t1; t1 = t1->next; } } void sub(list *&a, list *&b) { list *p1, *p2; p1 = a; p2 = b; while (p1) { while (p2) { if (p1->val == p2->val) del(p1, p1->val); p2 = p2->next; } p1 = p1->next; } } int main() { setlocale(LC_ALL, "Russian"); list *p1 = new list; list *p2 = new list; p1 = init(5); add(p1, 6); add(p1, 9); p2 = init(6); add(p2, 7); sub(p1, p2); print(p1); cout << endl; print(p2); delete p1; delete p2; _getch(); return 0; } 

The sub list difference function does not work. I can not understand what the error is.

  • one
    Try to write more detailed questions. Explain exactly what you see the problem, how to reproduce it, etc. - Nicolas Chabanovsky

1 answer 1

The sub method is completely incorrect.

See what you are doing. In the first iteration of the outer loop, you compare all the elements of the second list with the head element of the first. Then you do not reinitialize p2 , and in subsequent iterations it remains NULL . Thus, further iterations do nothing at all.

See what needs to be done. Notice that the del method deletes the value in the entire list. Therefore, it should be enough for you to run through the second list and call del for each element of the second list:

 for (list *p2 = b; p2; p2 = p2->next) del(a, p2->val); 

or staying in the style of your code

 list *p2; p2 = b; while (p2) { del(a, p2->val); p2 = p2->next; } 

Note that you need to delete on a , and not on its copy p1 , because the procedure del can modify the passed pointer.

There are surely some errors in the code. For example, you have a memory loss at the beginning of main ( list *p1 = new list; - this value is immediately lost). (And at the end: for the mastering of the memory of the list, a simple delete not enough.)