how to delete dynamic objects

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
//
#include <iostream>
using namespace std;

class node
{
private:
public:	
	int data;
	node *next;
	node(int d, node *p): data(d), next(p){}
};

int main()
{
	int n;
	node *p=nullptr;
	node *q=nullptr;
	cout << "num = ";

	while (cin >> n)  ///how can i put cin inside loop?
	{
		p = new node(n,q);
		q=p;
		cout << "n = ";
	}	

	while(p->next)
	{
		cout<< p->data << " ";  ///why first input not Shown?
		p=p->next;
	}
	cout<<"\n";

        ///How to delete the allocated memory?

return 0;
}
Last edited on
The simplest way is to use C++'s own linked lists. Since you have nullptr, you have std::forward_list (otherwise you can use std::list with no changes to the program)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <forward_list>

int main()
{
    std::forward_list<int> p;
    std::cout << "num = ";
    int n;
    while(std::cin >> n)
    {   
        p.push_front(n);
        std::cout << "n = ";
    }

    for(int n: p)
        std::cout<< n << " ";
    std::cout << '\n';
}

demo: http://coliru.stacked-crooked.com/a/03a4ee09cc9b07e8

In general, you delete dynamically-allocated objects by creating classes that manage these objects, like forward_list does in this example. Its destructor walks the list with an equivalent of your while(p->next) p=p->next and calls delete on each node.

(btw, to print the first input, change line 33 to cout << p->data << "\n"; You should also protect your program from non-numeric or empty input, which is where it crashes on p->next: mine doesn't)
Last edited on
Topic archived. No new replies allowed.