Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Linked Lists in C
#12
Code:
int compare(struct integer *p, struct integer *q)
{
    
    int j;
    
    while  (p != NULL){
           if(q==NULL){
             return 1;}
             else if (q!=NULL){
                          if (p>q){
                                   j=1;}
                          else if (p<q){
                                   j= -1;}
                          else if (p==q){
                                   j= 0;}
                                   }
             p= p->next;
             q= q->next;
            
            
             }
            
            
return (j);            
}
returns, for the numbers above, -1, -1, 1, -1, -1. Which is wrong for the first and last one. Whereas

Code:
int compare(struct integer *p, struct integer *q)
{
    int c;
    
  if (p == NULL) return -1;
  if (q == NULL) return 1;
  // or vice versa
  if (p->next != NULL && q -> next != NULL) {
   c = compare(p->next, q->next);
   if (c == 0) {
    if (p > q) return 1;
    if (q > p) return -1;
    else return 0;
   }
   else return c;
  }
  else return 0;
}

returns all -1s, which is wrong for the first, third, and last ones. The only thing i changed in your code was i added a semicolon after c = compare(p->next, q->next) since it wouldnt let me compile, and capitalized the null to NULL. And I declared c, since it was undeclared.
Reply


Messages In This Thread
Linked Lists in C - by Sivrat - 2010-09-14, 02:38 PM
Linked Lists in C - by Fiel - 2010-09-14, 02:41 PM
Linked Lists in C - by Sivrat - 2010-09-14, 02:50 PM
Linked Lists in C - by Fiel - 2010-09-14, 03:00 PM
Linked Lists in C - by Stereo - 2010-09-14, 09:37 PM
Linked Lists in C - by Sivrat - 2010-09-15, 11:54 AM
Linked Lists in C - by Stereo - 2010-09-15, 03:44 PM
Linked Lists in C - by Sivrat - 2010-09-15, 05:29 PM
Linked Lists in C - by Stereo - 2010-09-15, 06:10 PM
Linked Lists in C - by Sivrat - 2010-09-15, 07:49 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:10 PM
Linked Lists in C - by Sivrat - 2010-09-15, 08:17 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:39 PM
Linked Lists in C - by Sivrat - 2010-09-15, 08:45 PM
Linked Lists in C - by Stereo - 2010-09-15, 08:54 PM
Linked Lists in C - by Sivrat - 2010-09-15, 09:02 PM
Linked Lists in C - by Sivrat - 2010-09-15, 10:56 PM

Forum Jump:


Users browsing this thread: 1 Guest(s)