clear dynamic linked list

how do I do to clear this list and deallocate the dynamic memory, I have gived it a try but I obviously do some kind of logical error couse I don't get out of my clear function. perhaps I "clear" in the wrong way too.
could anyone help/explain please?










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
#include <iostream>

using namespace std;
struct List
{
  int data;
  List * next=nullptr;
};

void insert(List  *&p, int d);
void print(List *p);
void clear(List *p);
int main()
{
  // List *p=new List;
  List *p=nullptr;

  int data;
  while(cin>>data)
    {
      insert(p,data);

    }

  print(p);
  clear(p);
  print(p);
  return 0;
}


void insert(List  *&p, int d)
{
  if(p == nullptr ||  p->data > d)
    {
      List *pekare=new List;
      pekare->data=d;
      pekare->next=p;
      p=pekare;
      pekare=nullptr;
    }
  else if(p->data < d)
    {
      insert(p->next,d);
    } 
}
void print(List *p)
{
  while(p->next!=nullptr)
    {
      cout<<p->data<<" ";
      p=p->next;
    }
cout<<p->data<<" ";
  cout<<endl;
}
void clear(List *p)
{
  List *pekare=p;
  while(pekare->next!=nullptr)
    {
      List *prev=p;
      p=pekare;


      while(p->next!=nullptr)
	{
	  prev=p;
	  p=p->next;
	}
      delete p;
      delete prev;
      prev=nullptr;
    }
  /*
  if(p !=nullptr)
    {
      clear(p->next);
      
    }
  delete p;
  p=nullptr;
  */
}

For example it can look the following way

1
2
3
4
5
6
7
8
9
10
11
List * clear( List *p )
{
   while ( p )
   {
      List *tmp = p;
      p = p->next;
      delete tmp;
   }

   return nullptr;
}


and be called as

p = clear( p );

Or

1
2
3
4
5
6
7
8
9
10
11
12
void clear( List * &p )
{
   List *q = p;
   p = nullptr;

   while ( q )
   {
      List *tmp = q;
      q = q->next;
      delete tmp;
   }
}


and be called as

clear( p );
Last edited on
Topic archived. No new replies allowed.