clearone data in dynamic list.

I'm trying to clear one data of the dynamic list, with no success for a while now and I keep getting segmentation fault and I can't figure out what i'm doing wrong couse, I've tried to "sketch it up" before writing it more than once.
the fault is in function clearone





1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void clearone(List*&p,int d)
{
  if( ( (p->data == d) && (p->next == nullptr) ) )
    {
      delete p;
      p=nullptr;
    }
   else if(p->data!=d && p->next!=nullptr)
    {
      clearone(p,d);
    }
  else if( ( (p->data == d) && (p->next ) ) )
    {
      List *tmp = p;
      p=p->next;
      delete tmp;
      tmp=nullptr;
    }
}




hole programme

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

using namespace std;
struct List
{
  int data;
  List * next=nullptr;
};
void insert(List  *&p, int d);
void print(List *p);
List * clear(List *p);
void clearone(List*&p,int d);


int main()
{
  // List *p=new List;
  List *p=nullptr;

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

    }

  print(p);
  clearone(p,5);
  print(p);

  p= clear(p);
  if(p!=nullptr)
    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);
    } 
  else if((p->data = d))
    {
      List *pekare=new List;
      pekare->data=d;
      pekare->next=p;
      p=pekare;
      pekare=nullptr;
      delete pekare;
    }
}
void print(List *p)
{


  while(p->next!=nullptr)
    {
      cout<<p->data<<" ";
      p=p->next;
    }
cout<<p->data<<" ";
  cout<<endl;
}	
List * clear( List *p )
{
   while ( p )
   {
      List *tmp = p;
      p = p->next;
      delete tmp;
   } return nullptr;
}

     
void clearone(List*&p,int d)
{
  if( ( (p->data == d) && (p->next == nullptr) ) )
    {
      delete p;
      p=nullptr;
    }
   else if(p->data!=d && p->next!=nullptr)
    {
      clearone(p,d);
    }
  else if( ( (p->data == d) && (p->next ) ) )
    {
      List *tmp = p;
      p=p->next;
      delete tmp;
      tmp=nullptr;
    }
}
Last edited on
Line 10: clearone(p->next, d);
Topic archived. No new replies allowed.