0

I am trying to create a list of nodes and then put numbers in them.. I can do that. But I need help trying to sort the nodes. Here is my program.

Thank you,
Brian

int null = -1;
typedef struct Node { 
   int val;
   Node next;
   Node(int v, Node t){
        val = v;
        next = t;
        }//node    
} Node;

Node sort(Node a);

int main() {
   Node a = new Node(0, null); 
   
   for(int i=1;i<=10;i++) {                
      Node b = new Node(0, null);             //create b node
      b.val = rand();                 //fill b node with random numbers
      b.back  = a;
      a = b;
   }
   Node m = sort(a);            //sort nodes pass to m node
   while(m) {
      cout << m.val << " ";      //print out nodes      
      m = m.next ;
   }
   return 0;
}

Node sort(Node a){                       //sorts nodes
    Node  b = new Node(0, null);
    Node  x, u, t;
    
    while(a.next != null){
       t = a.next;
       u = t.next;
       a.next = u;
       for(x = a; x.next != null; x = x.next)
          if(x->next.val > t.val) break;
       t.next = x.next; x.next = t; 
   }      
   return b;
}// sort
3
Contributors
2
Replies
3
Views
12 Years
Discussion Span
Last Post by kafkanien
0

A struct cannot contain an instance of itself -- perhaps you meant to have a pointer to the next instance in the Node (and elsewhere).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.