Sorting Linked Lists

I'm looking to sort my linked lists from smallest to largest. I think I need to set my minvalue to head.

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


struct ListNode
	{
		double value;             //this value is in the node
		struct ListNode *next;   //to point to the next node
	};
	

	
int main()
{
	ListNode *head, *ptr, *minptr;
	
	ListNode node1, node2, node3;
	node1.value = 356;
	node2.value = 726;
	node3.value = 84;
	
	head = &node1;
	node1.next = &node2;
	node2.next = &node3;
	node3.next = NULL;
	
	ptr = head;
	double minvalue = 999;
	
	if (ptr->value < minvalue)
	{
		minvalue = ptr->value;
		minptr = ptr;
	}
	ptr = ptr->next;
	if (ptr->value < minvalue)
	{
		minvalue = ptr->value;
		minptr = ptr;
	}
	ptr = ptr->next;
	if (ptr->value < minvalue)
	{
		minvalue = ptr->value;
		minptr = ptr;
	}
	ptr = ptr->next;
	
	
	
	cout << head->value << endl;
	head = head->next;
	cout << head->value << endl;
	head = head->next;
	cout << head->value << endl;
	
	
	return 0;
}	
	
Why do you need to sort a linked lists? They are the worst possible structure to use for sorting.

Other than that, you would sort it the same way you would sort anything else. Please be more specific about what you are having trouble with.

If possible, take @anup30's suggestion below and use a standard library container. (Linked lists are not very useful in C++, especially for primitive types)
Last edited on
use forward_list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <forward_list>
using namespace std;

int main(){	

	forward_list<double> FL;
	
	FL.push_front(1.2);
	FL.push_front(0.2);
	FL.push_front(3.5);
	
	FL.sort();
	
	for(auto x: FL) { cout << x << " "; }
	cout << "\n";			
	
	return 0;
}
Topic archived. No new replies allowed.