Linked List Bubble Sort?
Oct 28, 2010 at 1:23am UTC
How is it possible to do a bubble sort for a linked list? I want to be able to sort the data in ascending order. I think my algorithm for my Sort method is incorrect, as I get the following error over "temp->getOneNumber()": Expression must be a modifiable lvalue. Doesn't it return a number though? Here is my whole program...
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 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
#include <iostream>
#include <cstdlib>
using namespace std;
class Node {
public :
Node* getNextPointer();
void putNextPointer(Node* x);
Node* putOneNumber(Node* x, int noun);
int getOneNumber();
int setOneNumber(int number);
private :
int n;
Node* nextPtr;
};
class BagList {
public :
BagList ();
bool putNumber(int n);
void display();
void sort();
private :
Node* ListPointer;
};
// Node Class Methods
Node* Node::getNextPointer (){
return nextPtr;}
void Node::putNextPointer (Node* x){
this ->nextPtr = x;}
Node* Node::putOneNumber (Node* x, int number) {
Node* temp = NULL;
if ((temp = new Node())) {
temp->nextPtr = x;
temp->n = number;}
return temp;}
int Node::getOneNumber() {
return n;}
int Node::setOneNumber(int number)
{n = number;
return n;}
// BagList Class Methods
BagList::BagList () {ListPointer = NULL;}
void BagList::display(){
Node *temp;
for (temp = ListPointer; temp!= NULL; temp = temp->getNextPointer())
cout<<temp->getOneNumber() <<" " ;
cout<<endl;
}
void BagList::sort(){
Node *temp;
int temp1;
for (bool didSwap = true ; didSwap; ){
didSwap = false ;
for (temp = ListPointer; temp!= NULL; temp = temp->getNextPointer())
{
if (temp->getOneNumber() > temp->getNextPointer()->getOneNumber())
{
temp1 = temp->getOneNumber();
temp->getOneNumber() = temp->setOneNumber(temp->getNextPointer()->getOneNumber());
temp->setOneNumber( temp->getNextPointer()->getOneNumber() = temp1;
didSwap = true ;
}
}
}
}
bool BagList::putNumber (int n) {
bool x = false ;
Node* temp1;
Node A;
temp1 = A.putOneNumber (ListPointer, n);
if (temp1 != NULL)
{ ListPointer = temp1;
x =true ;
}
return x;}
int main () {
BagList A;
int num;
cout << "Enter 10 numbers: " ;
for (int i=0; i<10; i++)
{
cin>>num;
if (!cin.eof()&&cin.good())
A.putNumber(num);
}
cout<<endl <<endl;
A.display(); //display numbers
A.sort(); //sort the numbers
A.display(); //display them in ascending order
system("pause" );
return 0;
}
Topic archived. No new replies allowed.