【发布时间】:2014-10-07 15:53:11
【问题描述】:
我是 C 的新手,我正在尝试编写一个链表,其中每个节点只包含一个 int。结构体的定义是可以的,但是我也想写方法来更新这个链表(在尾部添加元素并删除头部元素)。 (我希望能够读取最近添加的元素)
我写了下面的函数,但是我不知道free应该在哪里以及如何实现。谁能帮我解决这个问题?
typedef struct Node{
Node next = NULL;
int number;
} Node;
void add_node(Node *LL,int val){
// add node to the end of the linked list
new_node = (struct Node *)malloc(1*sizeof(struct Node));
new_node->number = val;
Node n = *LL;
while (n.next != NULL){
n = n.next;
}
n.next = new_node;
}
void delete_head(Node *LL){
// update the head
*LL = LL->next;
//free?
}
void update_LL(*LL,int val){
add_node(*LL,val);
delete_head(*LL);
}
【问题讨论】:
-
Node next = NULL;-->struct Node *next;in C. -
正如所写,无法从
delete_head中更新头部:它传递了一个指向头部节点的指针,但不知道该值存储在哪里,因此无法更新它.您可以(正如许多人所解释的那样)删除该节点,但是跟踪头的任何内容都需要更新为新头。
标签: c linked-list