1

美好的一天,堆栈溢出。

我有一个家庭作业,我在这个周末工作,但我遇到了一些问题。我们有一个结构“记录”(其中包含有关经销商汽车的信息),它根据 1)其品牌和 2)根据其车型年份放置在链接列表中的特定位置。

这是在最初构建列表时完成的,当在 Main 中调用“int insertRecordInAscendingOrder”函数时。在“insertRecordInAscendingOrder”中,调用了第三个函数“createRecord”,其中创建了链表。然后该函数转到函数“compareCars”以确定将哪些元素放在哪里。根据此函数返回的值,insertRecordInAscendingOrder 然后将记录放在它所属的位置。然后打印出该列表。还有更多的任务,但当我完成它时,我会越过那座桥。

理想情况下,为了使分配被认为是正确的,链表必须按以下顺序排列:

    Chevrolet 2012 25
    Chevrolet 2013 10
    Ford 2010 5
    Ford 2011 3
    Ford 2012 15
    Honda 2011 9
    Honda 2012 3
    Honda 2013 12
    Toyota 2009 2
    Toyota 2011 7
    Toyota 2013 20

从具有以下数据排序的文本文件中:

    Ford 2012 15
    Ford 2011 3
    Ford 2010 5
    Toyota 2011 7
    Toyota 2012 20
    Toyota 2009 2
    Honda 2011 9
    Honda 2012 3
    Honda 2013 12
    Chevrolet 2013 10
    Chevrolet 2012 25

请注意,“make”字段的字母顺序优先,然后,型号年份从最旧到最新排列。

但是,该程序将其作为最终列表生成:

    Chevrolet 2012 25
    Chevrolet 2013 10
    Honda 2011 9
    Honda 2012 3
    Honda 2013 12
    Toyota 2009 2
    Toyota 2011 7
    Toyota 2012 20
    Ford 2010 5
    Ford 2011 3
    Ford 2012 15

昨天我和一名研究生坐下来,试图解决所有这些问题,但我们只是不明白为什么它将福特节点踢到了列表的末尾。

这是代码。您会注意到,我在插入节点的每个实例中都包含了一个 printList 调用。通过这种方式,您可以看到节点按“顺序”排列时发生的情况。它在 ANSI C99 中。所有函数调用都必须按照指定进行,所以不幸的是,没有真正的方法可以通过创建更有效的算法来解决这个问题。

    #include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 50
#define MAX_MAKE 20

typedef struct record
{
    char *make;
    int year;
    int stock;
    struct record *next;
} Record;

int compareCars(Record *car1, Record *car2);
void printList(Record *head);
Record* createRecord(char *make, int year, int stock);
int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock);

int main(int argc, char **argv)
{
    FILE *inFile = NULL;
    char line[MAX_LINE + 1];
    char *make, *yearStr, *stockStr;
    int year, stock, len;
    Record* headRecord = NULL;

    /*Input and file diagnostics*/
    if (argc!=2)
    {
        printf ("Filename not provided.\n");
        return 1;
    }

    if((inFile=fopen(argv[1], "r"))==NULL)
    {
        printf("Can't open the file\n");
        return 2;
    }

    /*obtain values for linked list*/
    while (fgets(line, MAX_LINE, inFile))
    {
        make = strtok(line, " ");
        yearStr = strtok(NULL, " ");
        stockStr = strtok(NULL, " ");
        year = atoi(yearStr);
        stock = atoi(stockStr);
        insertRecordInAscendingOrder(&headRecord,make, year, stock);

    }


    printf("The original list in ascending order: \n");
    printList(headRecord);
}

/*use strcmp to compare two makes*/

int compareCars(Record *car1, Record *car2)
{
    int compStrResult;
    compStrResult = strcmp(car1->make, car2->make);
    int compYearResult = 0;

    if(car1->year > car2->year)
    {
        compYearResult = 1;
    }
    else if(car1->year == car2->year)
    {
        compYearResult = 0;
    }
    else
    {
        compYearResult = -1;
    }

    if(compStrResult == 0 )
    {
        if(compYearResult == 1)
        {
            return 1;
        }
        else if(compYearResult == -1)
        {
            return -1;
        }
        else
        {
            return compStrResult;
        }
    }
    else if(compStrResult == 1)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock)
{
    Record *previous = *head;
    Record *newRecord = createRecord(make, year, stock);
    Record *current = *head;
    int compResult;

    if(*head == NULL)
    {
        *head = newRecord;
        printf("Head is null, list was empty\n");
        printList(*head);
        return 1;
    }
    else if ( compareCars(newRecord, *head)==-1) 
    {
        *head = newRecord;
        (*head)->next = current;
        printf("New record was less than the head, replacing\n");
        printList(*head);
        return 1;
    }
    else
    {
        printf("standard case, searching and inserting\n");
        previous = *head;

        while ( current != NULL &&(compareCars(newRecord, current)==1)) 
        {
            printList(*head);
            previous = current; 
            current = current->next; 
        }

        printList(*head);
        previous->next = newRecord;
        previous->next->next = current;
    }
    return 1;
}

/*creates records from info passed in from main via insertRecordInAscendingOrder.*/
Record* createRecord(char *make, int year, int stock)
{
    printf("CreateRecord\n");
    Record *theRecord;
    int len;

    if(!make)
    {
        return NULL;
    }

    theRecord = malloc(sizeof(Record));

    if(!theRecord)
    {
        printf("Unable to allocate memory for the structure.\n");
        return NULL;
    }

    theRecord->year = year;
    theRecord->stock = stock;

    len = strlen(make);
    theRecord->make = malloc(len + 1);
    strncpy(theRecord->make, make, len);
    theRecord->make[len] = '\0';
    theRecord->next=NULL;

    return theRecord;
}

/*prints list. lists print.*/
void printList(Record *head)
{
    int i;
    int j = 50;
    Record *aRecord;
    aRecord = head;

    for(i = 0; i < j; i++)
    {
        printf("-");
    }
    printf("\n");
    printf("%20s%20s%10s\n", "Make", "Year", "Stock");

    for(i = 0; i < j; i++)
    {
        printf("-");
    }
    printf("\n");

    while(aRecord != NULL)
    {       
        printf("%20s%20d%10d\n", aRecord->make, aRecord->year,
        aRecord->stock);        
        aRecord = aRecord->next;
    }
    printf("\n");
}

命令行参数所需的文本文件可以以您喜欢的任何名称保存;以下是您需要的内容:

    Ford 2012 15
    Ford 2011 3
    Ford 2010 5
    Toyota 2011 7
    Toyota 2012 20
    Toyota 2009 2
    Honda 2011 9
    Honda 2012 3
    Honda 2013 12
    Chevrolet 2013 10
    Chevrolet 2012 25

在此先感谢您的帮助。我将继续自己耕耘。

4

3 回答 3

2

问题是

else if(compStrResult == 1)

你检查一个特定的返回值strcmp. 规范只说在各自的情况下结果是正数、负数或零,并且通常是第一个不同字符之间的差异。你应该检查

if (compStrResult > 0)

那里。

于 2012-10-13T21:18:12.070 回答
0

编写一个非常简单的测试套件会告诉您错误在 compareCars 中。

由于年份的比较相当直接,请查看 strcmp 的文档:它不返回 0、1 或 -1,而是返回 0 或正整数或负整数。

int compareCars(Record *car1, Record *car2)
{
    int makecmp = strcmp(car1->make, car2->make);

    if( makecmp > 0 )
      return 1;

    if( makecmp == 0 )
    {
        if (car1->year > car2->year)
          return 1;
        if( car1->year == car2->year )
          return 0;
    }

    return -1;
}

该功能的示例测试套件:

#include <assert.h>

void main()
{
  Record c1 = {"Toyota", 1991};
  Record c2 = {"Toyota", 1992};
  Record c3 = {"Ford", 1991};
  Record c4 = {"Ford", 1992};

  assert( compareCars( &c1, &c2 ) == -1 );
  assert( compareCars( &c1, &c1 ) == 0 );
  assert( compareCars( &c2, &c1 ) == 1 );
  assert( compareCars( &c2, &c3 ) == 1 );
  assert( compareCars( &c3, &c2 ) == -1 );
  assert( compareCars( &c3, &c4 ) == -1 );
  assert( compareCars( &c4, &c3 ) == 1 );
  assert( compareCars( &c4, &c1 ) == -1 );
}

然后,请注意:在 createRecord 中我建议使用 ofstrdup代替 malloc/strncpy 和朋友。

于 2012-10-13T21:27:12.243 回答
0

无论如何:修复后的代码;致力于编码风格

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_LINE 50
#define MAX_MAKE 20

typedef struct record
{
    char *make;
    int year;
    int stock;
    struct record *next;
} Record;

int compareCars(Record *car1, Record *car2);
void printList(Record *head);
Record* createRecord(char *make, int year, int stock);
int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock);

int main(int argc, char **argv)
{
    FILE *inFile = NULL;
    char line[MAX_LINE + 1];
    char *make, *yearStr, *stockStr;
    int year, stock, len;
    Record* headRecord = NULL;

    /*Input and file diagnostics*/
    if (argc!=2)
    {
        printf ("Filename not provided.\n");
        return 1;
    }

    if((inFile=fopen(argv[1], "r"))==NULL)
    {
        printf("Can't open the file\n");
        return 2;
    }

    /*obtain values for linked list*/
    while (fgets(line, MAX_LINE, inFile))
    {
        make = strtok(line, " ");
        yearStr = strtok(NULL, " ");
        stockStr = strtok(NULL, " ");
        year = atoi(yearStr);
        stock = atoi(stockStr);

       // fprintf (stderr, "Record read Make[%s] Year[%d] Stock[%d]", make, year, stock);
        insertRecordInAscendingOrder(&headRecord,make, year, stock);

    }


    printf("The original list in ascending order: \n");
    printList(headRecord);

    scanf ("%d", &len);

    return 0;
}

/*use strcmp to compare two makes*/

int compareCars(Record *car1, Record *car2)
{
    int compStrResult;
    compStrResult = strcmp(car1->make, car2->make);
    int compYearResult = 0;

    if(car1->year > car2->year)
    {
        compYearResult = 1;
    }
    else if(car1->year == car2->year)
    {
        compYearResult = 0;
    }
    else
    {
        compYearResult = -1;
    }

    if(compStrResult == 0 )
    {
        if(compYearResult == 1)
        {
            return 1;
        }
        else if(compYearResult == -1)
        {
            return -1;
        }
        else
        {
            return compStrResult;
        }
    }
    else if(compStrResult > 0)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

int insertRecordInAscendingOrder(Record **head, char *make, int year, int stock)
{
    Record *previous = *head;
    Record *newRecord = createRecord(make, year, stock);
    Record *current = *head;
    //int compResult;

    if(*head == NULL)
    {
        *head = newRecord;
        printf("Head is null, list was empty\n");
        //printList(*head);
        return 1;
    }
    else if ( compareCars(newRecord, *head)==-1)
    {
        *head = newRecord;
        (*head)->next = current;
        printf("New record was less than the head, replacing\n");
        //printList(*head);
        return 1;
    }
    else
    {
        printf("standard case, searching and inserting\n");
        previous = *head;

        while ( current != NULL &&(compareCars(newRecord, current)==1))
        {
            //printList(*head);
            previous = current;
            current = current->next;
        }

        //printList(*head);
        previous->next = newRecord;
        previous->next->next = current;
    }
    return 1;
}

/*creates records from info passed in from main via insertRecordInAscendingOrder.*/
Record* createRecord(char *make, int year, int stock)
{
    printf("CreateRecord\n");
    Record *theRecord;
    int len;

    if(!make)
    {
        return NULL;
    }

    theRecord = malloc(sizeof(Record));

    if(!theRecord)
    {
        printf("Unable to allocate memory for the structure.\n");
        return NULL;
    }

    theRecord->year = year;
    theRecord->stock = stock;

    len = strlen(make);
    theRecord->make = malloc(len + 1);
    strncpy(theRecord->make, make, len);
    theRecord->make[len] = '\0';
    theRecord->next=NULL;

    return theRecord;
}

/*prints list. lists print.*/
void printList(Record *head)
{
    int i;
    int j = 50;
    Record *aRecord;
    aRecord = head;

    for(i = 0; i < j; i++)
    {
        printf("-");
    }
    printf("\n");
    printf("%20s%20s%10s\n", "Make", "Year", "Stock");

    for(i = 0; i < j; i++)
    {
        printf("-");
    }
    printf("\n");

    while(aRecord != NULL)
    {
        printf("%20s%20d%10d\n", aRecord->make, aRecord->year,
        aRecord->stock);
        aRecord = aRecord->next;
    }
    printf("\n");
}
于 2012-10-13T21:33:45.790 回答