假设结构列表和节点定义为
struct list {struct node *a;};
struct node { int value;
struct node *next;};
以下函数将整数e作为第一个元素
插入到l中void insert_first(int e, struct list *l){
struct node * r = malloc(sizeof(struct node));
r->value = e;
r->next = l->a;
l->a = r;}
示例:原始列表“b”:1 2 3 4
调用insert_first(3,* b)
之后列出“b”:3 1 2 3 4
insert_first非常直接;但是,我很难弄清楚如何编写一个函数insert_last,它插入一个数字作为列表的最后一个元素。
示例:原始列表“b”:1 2 3 4
调用insert_last(3,* b)
之后列出“b”:1 2 3 4 3
感谢您提前提供任何帮助。
答案 0 :(得分:0)
您需要保存原始HEAD节点并遍历列表。希望这段代码可以帮到你。
struct node {
int value;
struct node *next;
};
struct list {struct node *a;};
struct node *insert_last(int e, struct list *l) {
/* Store the initial head of the list */
struct list *org_head = head;
struct node *r = malloc(sizeof(struct node));
r->value = e;
r->next = NULL /* Assign next pointer of current node to NULL */
/* If the head is initially NULL, then directly return the new created node (r) as the head of a linked list with only one node */
if(head == NULL)
{
return r;
}
/* While we do not reach the last node, move to the next node */
while(head -> next != NULL)
head = head -> next;
/* Assign the 'next' pointer of the current node to the "r" */
head->next = r;
/* return the original head that we have stored separately before */
return org_head;
}
答案 1 :(得分:0)
这样做的一种方法是迭代列表,直到找到尾部。像这样:
void insert_last(int e, struct list *l)
{
// "iter" Will iterate over the list.
struct node *iter = l->a;
struct node *new_node = malloc(sizeof(struct node));
// Advice: ALWAYS check, if malloc returned a pointer!
if(!new_node) exit(1); // Memory allocation failure.
new_node->value = e;
new_node->next = NULL;
if(iter){
// Loop until we found the tail.
// (The node with no next node)
while(iter->next) iter = iter->next;
// Assign the new tail.
iter->next = new_node;
}else{
// The list was empty, assign the new node to be the head of the list.
l->a = new_node;
}
}
编辑:我在你的代码中看到的东西,真的让我感到困惑:在使用malloc时,总是检查你是否确实有一个指针返回(检查指针是否为NULL)。如果malloc错误地分配内存,无论是缺少内存还是其他一些严重错误,它都会抛出一个NULL指针。如果你没有检查,你最终可能会遇到一些非常讨厌的,很难检测到的错误。只是提醒一下!