inserting sorted linked list

i am making a program that inserts data in a sorted linked list(in increasing order)

this is my code:
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
#include <iostream>
using namespace std;

class Node
{
  int data;
  Node *next;

 public:

  Node()
  {
    data = 0;
    next = NULL;
  }

  Node(int d)
  {
    data = d;
    next = NULL;
  }

  Node(int d, Node *n)
  {
    data = d;
    next = n;
  }

  int getData()
  {
    return data;
  }

  Node *getNext()
  {
    return next;
  }

  void setData(int d)
  {
    data = d;
  }

  void setNext(Node *n)
  {
    next = n;
  }
};

void sortedInsert(Node * &List, int d)
{
	if(List == NULL)
	{
	   List = new Node(d);
	}
	else
	{
        Node *temp = List;
        while(temp->getNext()!= NULL)
        {
           temp = temp->getNext();
        }
           temp->setNext(new Node(d));
    }
}

int main()
{
  Node *List = NULL;
  sortedInsert(List, 30);
  sortedInsert(List, 100);
  sortedInsert(List, 45);

  Node *t = List;
  while (t != NULL)
  {
    cout << t->getData() << endl;
    t = t->getNext();
  }
  
  system("pause");
  return 0;
}


ang this is the output :

30
100
45


but this should be the output:

30
40
100


can anyonehelp me with thise..i'm running out of ideas..
All your while loop does @line 61 is go to the end of the list. It needs something like:
while(temp->getNext() != NULL && temp.getData() < d)
closed account (o3hC5Di1)
Hi there,

Consider this function:

50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void sortedInsert(Node * &List, int d)
{
	if(List == NULL)
	{
	   List = new Node(d);
	}
	else
	{
        Node *temp = List;
        while(temp->getNext()!= NULL)
        {
           temp = temp->getNext();
        }
           temp->setNext(new Node(d));
    }
}


In order for the container to be sorted, there should be some sort of comparison between the existing elements.

So you need to check in your while loop, whether the current value is smaller than the next value in the list. If it is bigger, it needs to go further down the list, when it's smaller, that means it needs to go in front of the next value.

Hope that gets you on your way, please do let us know if you have any further questions.

All the best,
NwN
Topic archived. No new replies allowed.