比较和从字符串插入到链接列表

时间:2017-04-13 17:29:13

标签: c string data-structures linked-list

我必须比较

“5-5-0”

“5-5-1”

首先是第一个数字,然后是第二个数字,最后是最后一个数字,以便找到正确的位置,以便我可以将它嵌入到我的链接列表中。

你可以帮帮我吗?

更确切地说:我读了一个文件。 该文件包含一些字符串和一些整数。对于第一个字符串部分,我必须为我的新节点插入一个位置。 例如;

“3-0-0” “3-2-1”

用户输入“3-1-1”。我必须创建一个链表节点,然后将此节点插入这两个字符串之间。

到目前为止,我已经尝试了 atoi strcmp 但无法管理它。

1 个答案:

答案 0 :(得分:0)

这是对您的问题的更广泛的答案。

这是你要找的吗?

是的,这足以使用strcmp

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

/*
** List macros
*/

#define LNEXT(list_cell)            ((list_cell)->next)
#define LTONEXT(list_cell)          ((list_cell) = LNEXT(list_cell))
#define LCONT(list_cell, t_type)    ((t_type)((list_cell)->content))
#define LSTR(list_cell)             LCONT(list_cell, char*)

typedef struct      s_list
{
    void            *content;
    size_t          content_size;
    struct s_list   *next;
}                   t_list;

/*
** Helpers
*/

void    *ft_memdup(void const *ptr, size_t size)
{
    void            *result;

    result = (void*)malloc(size);
    if (result == NULL)
        return (NULL);
    memcpy(result, ptr, size);
    return (result);
}

/*
** List functions
*/

t_list  *ft_lstnew(void const *content, size_t content_size)
{
    t_list  *result;

    result = (t_list*)malloc(sizeof(t_list));
    if (result == NULL)
        return (NULL);
    result->next = NULL;
    if (content == NULL)
    {
        result->content = NULL;
        result->content_size = 0;
    }
    else
    {
        result->content = ft_memdup(content, content_size);
        result->content_size = content_size;
    }
    return (result);
}

/*
** Recives a pointer to a comparison function
*/

void    ft_lstinsert(
            t_list **head,
            t_list *new_l,
            t_list *prev,
            int (*cmp)(void*, void*))
{
    if (*head == NULL)
        *head = new_l;
    else if (cmp((*head)->content, new_l->content) > 0)
    {
        new_l->next = *head;
        if (prev != NULL)
            prev->next = new_l;
        else
            *head = new_l;
    }
    else
        ft_lstinsert(&(LNEXT(*head)), new_l, *head, cmp);
}

/*
** Iterates through all nodes, and apply function f
*/

void    ft_lstiter(t_list *lst, void (*f)(t_list *elem))
{
    while (lst)
    {
        f(lst);
        lst = lst->next;
    }
}

void    print_node(t_list *node)
{
    printf("%s\n", LSTR(node));
}

void    add_str(t_list **head, char *buf)
{
    ft_lstinsert(head,
        ft_lstnew(buf, strlen(buf)),
        NULL,
        (int (*)(void*, void*))(&strcmp));
}

int             main()
{
    t_list  *head;

    head = NULL;
    add_str(&head, "5-5-1");
    add_str(&head, "5-5-0");
    add_str(&head, "5-5-3");
    add_str(&head, "5-5-2");
    add_str(&head, "1-5-3");

    ft_lstiter(head, &print_node);
}

产生以下结果:

1-5-3
5-5-0
5-5-1
5-5-2
5-5-3