Please help!
The following code is supposed to sort the nodes by switching the pointers
instead of data, but all I get is an infinite loop when I run it.
#include <stdio.h>
#include <cstdlib>
#define HOWMANY 20
using namespace std;
class Stack;
class Node
{
public:
Node (double);
friend class Stack;
private:
double data;
Node* next;
};
#define NodeNULL (Node *)(0)
Node::Node(double thisdata)ata(thisdata),next(NodeNULL)
{
}
class Stack
{
public:
Stack();
void push(double);
double pop();
void selectionsort();
private:
Node* top;
};
Stack::Stack():top(NodeNULL) { }
void Stack:ush(double newguy)
{
Node* tptr = new Node(newguy);
tptr->next = top;
top = tptr;
}
double Stack:op()
{
Node* tptr;
double tdata;
if(top==NodeNULL){
fprintf(stderr,"empty stack\n");
exit(1);
}
tdata = top->data;
tptr = top;
top = top->next;
delete tptr;
return(tdata);
}
void Stack::selectionsort()
{
int icount = 0;
int count = 0;
double bestvalue;
Node *i = top;
Node *iprev = i;
Node *j = top;
Node *jprev = i;
Node *iprevtemp;
Node *jprevtemp;
Node *tempi;
Node *tempj;
Node *temp2;
Node *tempjprev;
while (i->next != NodeNULL) {
bestvalue = i->data;
tempj = i;
jprev = i;
j = i->next;
while (j->next != NodeNULL) {
if (j->data < bestvalue) {
bestvalue = j->data;
tempjprev = jprev;
tempj = j;
}
jprev = j;
j = j->next;
}
//Switching
tempi = i;
iprevtemp = iprev;
jprevtemp = tempjprev;
jprevtemp->next = tempi;
iprevtemp->next = tempj;
temp2 = tempj->next;
tempj->next = tempi->next;
tempi->next = temp2;
i = tempj;
iprev = i;
i = i->next;
}
}
double genrand()
{
return(((double)(random())+1.0)/((double)(RAND_MAX)+2.0));
}
int main(int argc, char** argv)
{
int i;
Stack q;
srandom(123456789);
for(i=0;i<HOWMANY;i++) q.push(genrand());
q.selectionsort();
for(i=0;i<HOWMANY;i++) printf("%f\n",q.pop());
}