c-按字母顺序排列字符串的链表



在我正在做的实验室工作中,它应该允许用户将字符串一个接一个地输入到链表中,直到用户没有输入字符串为止。此时,程序将按第一个字母比较每个字符串,按字母顺序排列,然后显示它们。

我知道我必须使用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;
}

你可以通过这种方式

1-将该int num替换为任何字符数组

2-在compare函数中,尝试使用strcmp函数比较char数组的元素,然后根据compare()函数返回值。

3-用字符变量的数组替换每个num

最新更新