下面是對您的問題的更一般化的答案。
這是你在找什麼?
是的,這是足夠使用的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'實際上應該給你正確的順序。爲什麼它不起作用? –