修改链接列表中结构中的字段

时间:2012-10-14 21:26:11

标签: c list struct field

我无法修改链接列表的成员。我们有一个结构“记录”,声明如下:

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

包含经销商的汽车信息。

我们首先使用CLI参数指示的文本文件的输入创建链接列表,该文件文件与此完全相同:

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

这些值使用fgets读入变量,然后发送到“insertRecordInAsendingOrder”函数,然后调用“createRecord”实际创建链表中的每个单独记录。然后insertRecordInAscendingOrder将记录放入列表中的适当位置。然后使用函数“printList”以排序的顺序打印出原始列表。

从这里开始,我们继续更新链表的其中一个成员的库存。值“Ford”(用于制造),“2012”(用于年份)和“12”(用于newStock字段)硬编码到功能“Main”中,并发送到“updateStockOfCar”功能,这是以下代码:

int updateStockOfCar(Record *head, char *make, int year, int newStock)
{
        if(head == NULL)
        {
            printf("The list is empty\n");
            return 0;
        }

        Record * matching = malloc(sizeof(Record));
        matching->make = make;
        matching->year = year;

        //If the first record is the one we want to modify, then do so
        if(strcmp(head->make, matching->make) == 0)
        {
            if(head->year == matching->year)
            {
                head->stock = newStock;
                return 1;
            }

            Record* previous = head;
            Record* current = head->next;

                //Loop through the list, looking for the record to update
            while(current != NULL)
            {
                if(strcmp(current->make, matching->make) == 0 && current->year  == matching->year)
                {
                    current->stock = newStock;
                    return 1;
                }
                else
                {
                    previous = current;
                    current = current -> next;
                }
            }
        }
        return 0;
}

正如您所看到的,此函数接收列表的头节点(我们开始搜索要更新的正确节点),make& year(对于我们的目标是修改库存的节点)和newStock(我们将用于替换目标节点中标准“stock”字段的值)。

我们的第一种情况是如果head为NULL,在这种情况下,我们说列表是空的并且返回一个不成功的“0”回到“Main”中的调用变量。

我们的第二种情况是,如果匹配中头部的make字段之间的strcmp是相同的,并且head和matching中的year字段是相同的,那么我们将head的stock字段更新为newStock并返回成功的“1”返回功能“主”。实质上,如果头节点是要修改的正确节点,我们就是这样做的。

我们的第三种情况是头节点不是要修改的正确节点。在当前(定义为头开始)不为NULL的情况下,我们将当前节点的make和year字段与我们想要更改的目标节点进行比较。如果它们匹配,我们将当前的库存字段设置为newStock并返回成功的“1”。如果它们不匹配,我们将经历“其他”条件,遍历列表直到找到我们正在寻找的那个,在这种情况下,我们更新当前的库存字段。

如果所有这些情况都失败了,那么第四个案例就会出现,将不成功的“0”返回到main,表明目标记录在链表中不存在。

但是,当编译并执行代码(我在下面提供给你)时,会为程序的输出生成以下内容:

The original list in ascending order: 
--------------------------------------------------
                Make                Year     Stock
--------------------------------------------------
           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                2012        20


====Update Stock of Car====
Failed to update stock. Please make sure the car that has the make/year exists in the  list.

====Removing a Record====
I'm trying to remove the record of Ford 2012...
Removed the record successfully. Printing out the new list...
--------------------------------------------------
                Make                Year     Stock
--------------------------------------------------
           Chevrolet                2012        25
           Chevrolet                2013        10
                Ford                2010         5
                Ford                2011         3
               Honda                2011         9
               Honda                2012         3
               Honda                2013        12
              Toyota                2009         2
              Toyota                2011         7
              Toyota                2012        20


====Insert Record in Ascending Order====
I'm trying to insert a record of make Jeep year 2011 stock 5...
Inserted the record successfully. Printing out the new list...
--------------------------------------------------
                Make                Year     Stock
--------------------------------------------------
           Chevrolet                2012        25
           Chevrolet                2013        10
                Ford                2010         5
                Ford                2011         3
               Honda                2011         9
               Honda                2012         3
               Honda                2013        12
                Jeep                2011         5
              Toyota                2009         2
              Toyota                2011         7
              Toyota                2012        20


I'm trying to insert a record of make Honda, year 2012, and stock 10...
Inserted the record successfully. Printing out the new list...
--------------------------------------------------
                Make                Year     Stock
--------------------------------------------------
           Chevrolet                2012        25
           Chevrolet                2013        10
                Ford                2010         5
                Ford                2011         3
               Honda                2011         9
               Honda                2012        10
               Honda                2012         3
               Honda                2013        12
                Jeep                2011         5
              Toyota                2009         2
              Toyota                2011         7
              Toyota                2012        20

由于某种原因,即使它存在于列表中,也会告诉“Main”函数未找到节点。

这是整个程序,虽然有更多功能有问题,但我排除了大部分功能:

/*homework2stackoverflow2.c*/

#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 removeRecord(Record **head, char *make, int year);
int updateStockOfCar(Record *head, char *make, int year, int newStock);

int main(int argc, char **argv)
/*START MAIN*/
{
    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);

    }

/*START PRINT ORIGINAL LIST*/
    printf("The original list in ascending order: \n");
    printList(headRecord);
/*END PRINT ORIGINAL LIST*/

/*START UPDATE STOCK TEST*/
    printf("\n====Update Stock of Car====\n");
    int newStock = 12;
    char* newMake = "Ford";
    int updateStatus = updateStockOfCar(headRecord, newMake, year, newStock);
    if(updateStatus == 0)
    {
        printf("Failed to update stock. Please make sure the car that has the make/year exists in the list.\n");

    }
    if(updateStatus == 1)
    {
        printf("Updated stock successfully. Printing out the new list...\n");
        printList(headRecord);
    }
/*END UPDATE STOCK TEST*/

/*START REMOVE RECORD TEST*/
    printf("\n====Removing a Record====\n");
    char *deleteMake = "Ford";
    int deleteYear = 2012;
    int removeStatus = removeRecord(&headRecord, deleteMake, deleteYear);

    if(removeStatus == 0)
    {
        printf("Failed to remove the record. Please make sure the care that has the make/year exists in the list.\n");
    }
    if(removeStatus == 1)
    {
        printf("Removed the record successfully. Printing out the new list...\n");
        printList(headRecord);
    }
/*END REMOVE RECORD TEST*/

/*START INSERT IN ASCENDING ORDER TEST*/
    printf("\n====Insert Record in Ascending Order====\n");
    char* insertMake = "Jeep";
    int insertYear = 2011;
    int insertStock = 5;
    int insertStatus = insertRecordInAscendingOrder(&headRecord, insertMake, insertYear, insertStock);
    printf("I'm trying to insert a record of make %s year %d stock %d...\n", insertMake, insertYear, insertStock);
    if(insertStatus == 0)
    {
        printf("Failed to insert the new record. Please make sure the car that has the make/year doesn't exist in the list.\n");        
    }
    if(insertStatus == 1)
    {
        printf("Inserted the record successfully. Printing out the new list...\n");
        printList(headRecord);
    }
    insertMake = "Honda";
    insertYear = 2012;
    insertStock = 10;
    insertStatus = insertRecordInAscendingOrder(&headRecord, insertMake, insertYear, insertStock);
    printf("\nI'm trying to insert a record of make %s, year %d, and stock %d...\n", insertMake, insertYear, insertStock);
    if(insertStatus == 0)
    {
        printf("Failed to insert the new record. Please make sure the car that has the make/year doesn't exist in the list.\n");        
    }
    if(insertStatus == 1)
    {
        printf("Inserted the record successfully. Printing out the new list...\n");
        printList(headRecord);
    }

/*END INSERT IN ASCENDING ORDER TEST*/

    fclose(inFile);
    return 0;
}
/*END MAIN*/

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;
}

/*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");
}

Record* createRecord(char *make, int year, int stock)
{
    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;
}

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

    if(*head == NULL)
    {
        *head = newRecord;
        //printf("Head is null, list was empty\n");
        return 1;
    }

    else if(compareCars(newRecord, *head) == 0)
    {   

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

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

        previous->next = newRecord;
        previous->next->next = current;
    }
    return 1;
}

int removeRecord(Record **head, char *make, int year)
{
    printf("I'm trying to remove the record of %s %d...\n", make, year);

    if(*head == NULL)
    {
        printf("The list is empty\n");
        return 0;
    }   

    Record * delete = malloc(sizeof(Record));
    delete->make = make;
    delete->year = year;

    //If the first record is the one we want to delete, then we need to update the head of the list and free it.
    if((strcmp((*head)->make, delete->make) == 0))
    {           
        if((*head)->year == delete->year)
        {               
            delete = *head;
            *head = (*head)->next;
            free(delete);
            return 1;
        }
    }

    Record * previous = *head;
    Record * current = (*head)->next;

    //Loop through the list, looking for the record to remove.
    while(current != NULL)
    {
        if(strcmp(current->make, delete->make) == 0 && current->year == delete->year)
        {       
            previous->next = current->next;
            free(current);
            return 1;
        }
        else
        {       
            previous = current;
            current = current->next;
        }
    }
    return 0;   
}

int updateStockOfCar(Record *head, char *make, int year, int newStock)
{
    if(head == NULL)
    {
        printf("The list is empty\n");
        return 0;
    }

    Record * matching = malloc(sizeof(Record));
    matching->make = make;
    matching->year = year;

    //If the first record is the one we want to modify, then do so
    if(strcmp(head->make, matching->make) == 0)
    {
        if(head->year == matching->year)
        {
            head->stock = newStock;
            return 1;
        }

        Record* previous = head;
        Record* current = head->next;

    //Loop through the list, looking for the record to update
        while(current != NULL)
        {
            if(strcmp(current->make, matching->make) == 0 && current->year == matching->year)
            {
                current->stock = newStock;
                return 1;
            }
            else
            {
                previous = current;
                current = current -> next;
            }
        }
    }
    return 0;
}

是什么导致这件事表明它不在列表中?

是的......这是一项家庭作业:P

3 个答案:

答案 0 :(得分:1)

我不完全清楚为什么你要分配一个新记录(正在泄露,顺便说一句)只是为了遍历链表并在找到节点后更新它。是否有问题:

int updateStockOfCar(Record *head, const char *make, int year, int newStock)
{
    Record* p = head;
    while (p)
    {
       if ((p->year == year) && !strcmp(p->make, make))
       {
          p->stock = newStock;
          break;
       }
       p = p->next;
    }
    return (p ? 1 : 0);
}

检索给定年/年的汽车当前库存:

int getStockOfCar(Record *head, const char *make, int year)
{
    Record* p = head;
    while (p)
    {
       if ((p->year == year) && !strcmp(p->make, make))
          return p->stock;
       p = p->next;
    }
    return 0;
}

或者我是否错过了问题中的要求(这不是第一次)。?

答案 1 :(得分:0)

  

值“Ford”(用于制造),“2012”(用于年份)和“12”(用于newStock字段)硬编码到功能“Main”中,并发送到“updateStockOfCar” “功能

“福特”和“12”是硬编码的,但“2012”不是......

此外,您永远不会free(matching)

答案 2 :(得分:0)

这里是固定代码,你把while循环放在第一个头匹配中如果是statment,应该在if语句之外

int updateStockOfCar(Record **head, char *make, int year, int newStock)
{
    if(*head == NULL)
    {
        printf("The list is empty\n");
        return 0;
    }

    Record * matching = malloc(sizeof(Record));
    matching->make = make;
    matching->year = year;

    //If the first record is the one we want to modify, then do so
    if(strcmp((*head)->make, matching->make) == 0)
    {
        if((*head)->year == matching->year)
        {
            (*head)->stock = newStock;
            return 1;
        }
    }

        Record* current = (*head)->next;

    //Loop through the list, looking for the record to update
    while(current != NULL) {
            if(strcmp(current->make, matching->make) == 0 && current->year == matching->year)
            {
                current->stock = newStock;
                return 1;
            }
            else
            {
                current = current -> next;
            }
    }
    return 0;
}