c-如何将索引分配给值​在链接列表中



我构建了一个链表,以int.的形式显示命令行上传递的参数

为了以后进行排序,我想以有序的方式为列表中的每个值分配索引。

例如/a.out-14 12 5 24分配的索引:[1][3][2][4]

这是一个学校作业,包括对堆叠在堆栈a上的每个值进行索引,将它们发送到堆栈B以便对它们进行排序,然后将它们发送回堆栈a。

索引是在每个节点中定义的int变量,因为我稍后将使用它来通过这些索引而不是通过它们的值来标识节点​​自身(更易于管理(

你知道如何进行吗?

这是我现在的代码

#include <stdlib.h>
#include <stdio.h>
typedef struct s_list   t_list;
struct  s_list
{
int     value;
int     index;
t_list  *next;
};
void    add_node_start(t_list **head, int value);
void    add_node_end(t_list **head, int value);
int     remove_first(t_list **head);
int     remove_last(t_list *head);
int     remove_by_index(t_list **head, int n);
void    print_list(t_list *head);
int     ft_atoi(const char *str);
void    add_node_start(t_list **head, int value)
{
t_list  *new;
new = malloc(sizeof(t_list));

new->value = value;
new->next = *head;
*head = new;
}
void    add_node_end(t_list **head, int value)
{
t_list  *current;
current = *head;

if (!*head)
{
add_node_start(head, value);
return ;
}

while (current->next != NULL)
current = current->next;

current->next = malloc(sizeof(t_list));
current->next->value = value;
current->next->next = NULL;
}
int remove_first(t_list **head)
{
t_list  *next_node;
int     retvalue;

retvalue = -1;
next_node = NULL;

if (*head == NULL)
return (-1);

next_node = (*head)->next;
retvalue = (*head)->value;
free(*head);
*head = next_node;
return (retvalue);
}
int remove_last(t_list *head)
{
t_list  *current;
int     retvalue;
retvalue = 0;
if (head->next == NULL)
{
retvalue = head->value;
free(head);
return (retvalue);
}

current = head;
while (current->next->next != NULL)
current = current->next;
retvalue = current->next->value;
free(current->next);
current->next = NULL;

return(retvalue);
} 
int remove_by_index(t_list **head, int n)
{
t_list  *current;
t_list  *temp_node;
int retvalue;
int i;

current = *head;
i = 0;
retvalue = -1;

if (n == 0)
return (remove_first(head));

while (i < n - 1)
{
if (current->next == NULL)
return (-1);
current = current->next;
i++;
}
temp_node = current->next;
retvalue = temp_node->value;
current->next = temp_node->next;
free(temp_node);
return(retvalue);
}
void    print_list(t_list *head)
{
t_list  *current;
current = head;

while (current != NULL)
{
printf("%dn", current->value);
current = current->next;
}
}
int main(int argc, char **argv)
{
t_list  *head;
int     i;
head = NULL;

i = 1;

while (i < argc)
{
add_node_end(&head, ft_atoi(argv[i]));
i++;
}
print_list(head);
return (0);
}

"索引";对于链接列表,取决于列表中节点的数量。它不应该是节点本身的属性,而应该只是从列表头开始一直计数到最后。

因此,为了得到具有"0"的节点;索引";n,只需使用一个简单的for循环,如:

t_list *current_node = head;
for (unsigned i = 0; i < n && current_node != NULL; ++i)
{
current_node = current_node->next;
}

当循环结束时,current_node将是空指针(因为n大于列表中的节点数(,或者它将是"0"处的节点;索引";n

最新更新