gpt4 book ai didi

比较字符串并将其插入到链接列表

转载 作者:行者123 更新时间:2023-11-30 16:47:14 25 4
gpt4 key购买 nike

我必须比较

“5-5-0”

“5-5-1”

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

你能帮我一下吗?

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

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

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

到目前为止,我已经尝试过 atoistrcmp 但无法成功。

最佳答案

这是针对您的问题的更通用的答案。

这是您要找的吗?

是的,使用 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

关于比较字符串并将其插入到链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43398369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com