在我正在进行的实验室工作中,应该允许用户逐个将字符串输入到链表中,直到用户不输入字符串。此时,程序将比较每个字符串的第一个字母,按字母顺序排列它们,然后显示它们。
我知道我必须使用strcmp来一次比较两个字符串,我试图理解这一点,但它太复杂了。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define StringLengthMAX 80
struct node_link
{
//char node_string[StringLengthMAX];
int num;
struct node_link *next;
};
int compare_node(struct node_link *b1, struct node_link *b2)
{
//strcmp(*b1, *b2);
if (b1 -> num < b2 -> num)
{
return -1;
}
if (b1 -> num == b2 -> num)
{
return 0;
}
if (b1 -> num > b2 -> num)
{
return 1;
}
}
struct node_link *add_node(struct node_link *list, struct node_link *node)
{
struct node_link *cur_node=list;
//case 1 : When list->num > node->num
if (compare_node(list, node) == 1)
{
node -> next = list;
list = node;
return list;
}
// case 2
while(cur_node->next != NULL)
{
if (compare_node(cur_node->next,node) == 1)
{
node -> next = cur_node -> next;
cur_node->next = node;
break;
}
else
{
cur_node = cur_node -> next;
}
}
// case 3 : node->next is the greatest
if (cur_node -> next == NULL)
{
cur_node->next = node;
}
return list;
}
void display_newlist(struct node_link *head)
{
struct node_link *node=head;
while(node != NULL)
{
printf("%d", node->num);
node = node->next;
printf(" ");
}
}
int main()
{
int a;
struct node_link *head;
struct node_link *node;
node = (struct node_link*)malloc(sizeof(struct node_link));
node->num = a;
node->next = NULL;
head = node;
do
{
puts("Please enter any number of integers, end inputs with a ZERO (0): ");
scanf("%d", &a);
node = (struct node_link*)malloc(sizeof(struct node_link));
node->num = a;
node->next = NULL;
head = add_node(head,node);
}while(a != 0);
display_newlist(head);
return 0;
}
答案 0 :(得分:0)
你可以通过这种方式做到这一点
1-将int num
替换为任何字符数组
2- in compare function尝试使用strcmp
函数比较char数组的元素,然后根据compare()
函数的值返回值。
3-用字符变量数组
替换evrynum