【问题标题】:Searching through a linked list.搜索链接列表。
【发布时间】:2014-11-02 14:58:46
【问题描述】:

所以我一直在尝试了解不使用使用 malloc 的 malloc 链表的定期定义结构之间的区别。

我现在遇到的问题是尝试搜索结构 (pi) 以查找成本大于搜索中输入的成本的每个零件号。到目前为止,这是我的整个程序。我为每个部分添加了 cmets。

我只是不确定我应该如何搜索每个结构以将其价格与搜索价格进行比较。

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

struct Item {
int quantity;
float cost;
char partNum[10];
struct Item *next;
};

void printItem(struct Item* pi);
void enterItem(struct Item* pi);

char search [100];

void main(int argc, char* argv[])
{
struct Item *pi;
struct Item *head;
int done = 0;
int i,j;
char choice;

//    ENTERING ITEM INTO THE STRUCTURE 
head = NULL;
while (!done) {
    printf("Enter another item? (y/n)");
    choice = getchar();
    if (choice == 'y' || choice == 'Y') {
        pi = (struct Item *)malloc(sizeof(struct Item));
        enterItem(pi);
        pi->next = head;
        head = pi;
    } else {
        done = 1;
    }
}
//    SEARCHING FOR ITEM BY PRICE
printf("Enter a price to find all items more expensive, or type 'exit':");
while (strcmp(search, "exit") !=0) {
    gets(search);
    for (j = 0; j<i ; i++) {
        if (strcmp(pi[j].cost, search) ==0) {
            printItem(pi);
            pi = pi->next;
        }
    }
}


}
getchar();
getchar();
}
// FUNCTION FOR PRINTING STRUCTURE ITEM
void printItem(struct Item* pi) {
printf("Quantity: %d\n", pi->quantity);
printf("Cost: $%.2f\n", pi->cost);
printf("Part # %s\n", pi->partNum);
printf("\n\n");
}

// FUNCITON FOR ENTERING IN NEW ITEM
void enterItem(struct Item* pi) {
printf("Quantity? ");
scanf("%d", &pi->quantity);
printf("Cost? ");
scanf("%f", &pi->cost);
getchar();   //need to clear out the carriage return from typeing in the cost
printf("Part Number? ");
gets(pi->partNum);
}

【问题讨论】:

  • for (j = 0; j&lt;i ; i++) 是一个奇怪的 for 循环,尤其是考虑到 i 从未被初始化。
  • 是的,我从另一段代码中添加了该部分,我必须搜索结构,而不是链接列表。所以我复制了它,希望我可以修改它来工作......没有走远。 @ooga
  • 这一行:for (j = 0; j
  • 这一行:pi = pi->next;需要移动到 if 代码块的右大括号之后,因此它会导致 pi 始终被步进到链表中的下一个条目
  • 代码创建了一个循环链表,那么'for'循环如何知道何时停止搜索呢?由于变量 'i' 未设置为链表中的条目数,因此搜索停止的时间完全取决于未初始化变量 'i' 中的(随机)值

标签: c pointers search linked-list malloc


【解决方案1】:

您做错的是将字符串(search 变量)与使用 strcmp 的浮点数(cost 变量)进行比较。这不会给你想要的输出。

相反,让我们使用-1 来表示exit,因为解析字符串并将其转换为浮点数是题外话。从head 开始迭代直到找到NULL,然后比较每个项目的价格。

float price;
struct Item *it = head;
printf("Enter a price to find all items more expensive, or type '-1' to exit:");
scanf("%f", price);

// check price for the 'exit' -- compare with -1

while (it != NULL) {
    if (it->cost > price)
            printItem(pi);

    it = it->next;
}

【讨论】:

  • 那么有什么方法可以使用 strcmp 来搜索价格吗?这确实有效,所以谢谢。 @qamyoncu
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 2018-07-19
  • 2011-08-03
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
相关资源
最近更新 更多