Bubble Sorting a linked list?

Hello, I am relatively new to C++ and am trying to bubble sort my linked list that creates 100 random integers. Everything works, but I am unsure how to continue this to include a bubble sorting method. Thanks for all the help!

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
#include "stdafx.h"
#include  <iostream>

using namespace std;

class Node{
public:
        int data; //set data
        Node * next; // set node next
        Node(int x){  
                data = x;  //data = whatever
                next = NULL; //next is null
        }

        Node(int x, Node *y){  //helps set the next step for the linkedlist
                data = x;
                next = y;
        }
};

class linkedList{   // my linked list class
        Node*head;
public:
        linkedList(){
                head = NULL;
        }
        void addNode(int value){    //adds nodes
                Node *p;
                if (head == NULL)
                        head = new Node(value, NULL);
                else{
                        p = head;
                        while (p->next != NULL)
                                p = p->next;
                        p->next = new Node(value, NULL);
                }
        }
        void print(){  // calls to print nodes
                Node * p;
                p = head;
                while (p != NULL){
                        cout << p->data << "\n";
                                p = p->next;
                }
        }

};

int main(void){  //main
        int random;
        linkedList get; //get linked list
        for (int x = 0; x < 20; x++){  //random integers loop
                random = rand() % 100 + 1;
                get.addNode(random);
                
        }
        get.print();
        return(0);
}
There are two ways to re-order a list. You either swap values or change links between the nodes. Your values (data) are cheap to swap.

The other part in sorting is the test, whether a swap is necessary. You'll have pointers to nodes, but you have to compare values:
1
2
3
4
5
6
Node * lhs = ...
Node * rhs = ...

if ( ! lhs < rhs ) // Wrong

if ( ! lhs->data < rhs->data ) // OK 
Topic archived. No new replies allowed.