【发布时间】:2019-06-12 03:36:28
【问题描述】:
我正在使用链表来存储结构。每个节点都有一个名为 item_t 的结构。 item_t 有一个名为 name 的字段。我想通过交换节点中的项目(item_t)按字母顺序对名称进行冒泡排序。该算法适用于数字(整数、浮点数等),但对字符串给出不正确的结果。
我猜问题隐藏在不正确使用 strcmp 中,但我阅读了所有文档,但看不到。
typedef struct item_t
/*
Definition of the item_t struct
*/
{
char *name;
float price;
}item_t;
/* structure for a node */
typedef struct node_t
{
item_t item;
struct node_t *next;
} node_t;
/* function to swap item of two nodes a and b*/
void swap(node_t *a, node_t *b)
{
item_t temp = a->item;
a->item = b->item;
b->item = temp;
}
void bubbleSortByNameAscending(node_t *start)
{
int swapped = 1;
node_t *ptr1;
node_t *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
while (swapped)
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (strcmp(ptr1->item.name, ptr1->next- >item.name) > 0)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
}
/* Bubble sort the given linked list */
void bubbleSortByPriceAscending(node_t *start)
/* TESTED */
{
int swapped;
node_t *ptr1;
node_t *lptr = NULL;
/* Checking for empty list */
if (start == NULL)
return;
do
{
swapped = 0;
ptr1 = start;
while (ptr1->next != lptr)
{
if (ptr1->item.price > ptr1->next->item.price)
{
swap(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
鉴于此列表:
- 列表项
- S7Edge 1500.00
- iPhone7 1000.00
- iOS10 0
- Android 0
按名称排序时,我期望得到以下结果:
- Android 0
- iOS 0
- iPhone7 1000.00
- iPhone8 2000.00
- S7Edge 1500.00
但我明白了:
- Android 0
- S7Edge 1500.00
- iOS 0
- iPhone7 1000.00
-
iPhone8 2000.00 然后我又添加了一个以 Z 开头的项目,以了解它的含义:
- Android 0
- iOS 0
- iPhone7 1000.00
- iPhone8 2000.00
- S7Edge 1500.00
- Zoidberg 0
我得到了:
- Android 0
- S7Edge 1500.00
- Zoidberg 0
- iOS 0
- iPhone7 1000.00
- iPhone8 2000.00
编辑:我很确定 'i' != 'I',而且 'Z' > 'i'。一个合乎逻辑的解决方案是将所有内容都小写或大写,然后 strcmp 但我如何将更改还原回来,以便“IPHONE”变为“iPhone”?
【问题讨论】:
-
您可能想使用
stricmp而不是strcmp,比较时它会忽略大小写。您说得对,原因是 ASCII 大写字母在前 -
请注意,
stricmp()是 Windows 函数,用于不区分大小写的字符串比较。 POSIX 系统上对应的函数是strcasecmp()来自标头<strings.h>(复数;C 标头是<string.h>)。
标签: c sorting linked-list alphabetical