#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; } } void add(list *&a, list *&head, int data) { list *p = new list; p->next = NULL; p->val = data; list *q = new list; q = head; if (a == NULL) a = p; else { while (q->next != NULL) q = q->next; q->next = new list; q = q->next; q->val = data; q->next = NULL; } a = q; } int main() { setlocale(LC_ALL, "Russian"); list *p1 = new list; list *head = NULL; add(p1, head, 5); add(p1, head, 6); print(p1); _getch(); return 0; } 

I can not understand what is wrong with the function of adding a new item to the list

Thanks for the advice. Here's a fix.

 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); } 
  • break add into simpler functions, and check them separately - Abyx
  • @Abyx, do not need there more simple. It is necessary to throw out a half of the code simply. - Qwertiy

2 answers 2

About the add function:

  1. Too many options. Only list and value are needed.
  2. There is no need to create so many junk lists. q=a and that's it.
  3. The case a==null handled separately by creating a list from one element.

After that, it should work.

Well, also, and who will free your memory for you?

  • And about the release of memory. There, in the message below, I created a new add function. And how do I free my memory now? Create a separate release function? Or after exiting the function, everything will be removed by itself? - zof
  • @zof, nothing you created through new itself will not be released. - Qwertiy

Of course, you can train with insertion to the end by viewing the list.

However, I highly recommend simply using two pointers to represent a simply linked list. The first is at the beginning, and the second is at the last element. Change them agreed and work with such a list easier. For an empty list, both are NULL. Further obvious.

This is if you generally need to insert at the end of the list. Usually, in practice, single-linked lists are used where the order of elements is not important.