Linked_List

I have this code, which generates 10 values randomly:

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

struct node{
	int value;
	node *next;
};

int main()
{
	srand(time(0));
	node *head;

	for(int i=0; i<10; i++){
		head = new node;
		head->value = rand()%10;

		head->next = NULL;

		cout<<head->value<<endl;
	}
	
	system ("pause");
	return 0;
}


Now I want to sort them in ascending order(or descending order). What should I do next? Anyone help plz.
Your code has a problem. You do create 10 nodes, but you point to only one of them. After the loop you can refer to that last created node, but the other have been forgotten. Thus, you don't create/have a list of ten elements.

Assuming you had a proper list, you would have to be able to swap values when they are not in order. Either swap the value fields, or rearrange links of the nodes to rearrange order of the nodes in the list.

There are many sorting algorithms. A bubble sort might be enough here.
Topic archived. No new replies allowed.