下面是对您的问题的更一般化的答案。
这是你在找什么?
是的,这是足够使用的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
可以粘贴你已经尝试过的代码,你有这个问题,所以我们可以提供帮助。 –
欢迎使用堆栈溢出。请尽快阅读[关于]和[问]页面。如果您未显示您尝试过的代码,我们无法提供帮助。请创建一个迄今为止竭尽全力的MCVE([MCVE]),然后我们可以帮助您。我们不会为您从头开始编写代码;我们确实帮助您解决您的问题,只要这是他们合理诚实的尝试。 –
如果''''符号周围的数字不超过'9',即不会变成两位或更多位数,那么'strcmp'实际上应该给你正确的顺序。为什么它不起作用? –