insert and print,linked list not working

I've been struggling trying to make a linked list where I insert numbers in the following order " 1 2 3 "
and then print them out.
how ever I do something wrong couse nothing get printed at all


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

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

void insert(List  *&p, int d);
void print(List *p);

int main()
{
  List *p=new List;
  int data;
  while(cin>>data)
    {
      insert(p,data);

    }
  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<<endl;
}

That is because you are never calling print()
And make condition of while loop in print() p!=nullptr
how embarrassing , how ever it still not work as it should
./a.out
23 4 5
0 4 5
the output isn't the same as the input .

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

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

void insert(List  *&p, int d);
void print(List *p);

int main()
{
  List *p=new List;
  int data;
  while(cin>>data)
    {
      insert(p,data);

    }

  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<<endl;
}
The problem is that p is not a nullptr when you call the function the first time, so whatever is in data is pure garbage could be pure garbage or just a default value, try replacing the first line in main with:
List *p=nullptr;
Last edited on
Topic archived. No new replies allowed.