您好,我是数据结构新手。所以我正在学习链表,主要问题是不同的人在教程中编码不同,这让我更加困惑。所以这是两个代码。 第一个是:
struct node {
int data;
struct node* next;
};
int main() {
struct node *head,*current;
head = malloc(sizeof(struct node));
head->data = 10;
head->next = NULL;
current = malloc(sizeof(struct node));
current->data = 20;
current->next = NULL;
head->next = current;
current = malloc(sizeof(struct node));
current->data = 50;
current->next = NULL;
head->next->next->next->next = current;
struct node* temp = head;
while(temp != NULL) {
printf("%d ",temp->data);
temp = temp->next;
}
我理解一切,但这里我的问题是 head->next = current 是如何工作的?我的意思是 current->next 始终保持为空,对吗?头部移动到当前,那么头部如何保持? 现在这里是上面的替代代码,只是为了避免多次编写 head->next->next->next。
struct node {
int data;
struct node *next;
};
int main() {
struct node *head = NULL;
struct node *current = NULL;
head = (struct node*) malloc(sizeof(struct node));
head->data = 10;
head->next = NULL;
current = head;
current->next = (struct node*) malloc(sizeof(struct node));
current = current->next;
current->data = 20;
current->next = NULL;
current->next = (struct node*) malloc(sizeof(struct node));
current = current->next;
current->data = 50;
current->next = NULL;
struct node *temp = head;
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->next;
}
在第二个代码中我实际上什么都不明白。这里 current = head 意味着将 current 指向第一个元素。那么为什么 current->next = (struct node*) malloc(sizeof(struct node)) 而不是 current = malloc(sizeof(struct node)) 。然后,当他们不使用 current = malloc(sizeof(struct node)) 时,如何使用 current->data。为什么 current = current->next?如果能详细解释一下就更好了。预先感谢。
说明: 将第一个节点和点头和电流分配给第一个节点:
head = (struct node*) malloc(sizeof(struct node));
head->data = 10;
head->next = NULL;
current = head;
将第一个节点的下一个指针设置为第二个分配的节点
current->next = (struct node*) malloc(sizeof(struct node));
将当前前进到第二个节点并设置数据
current = current->next;
current->data = 20;
current->next = NULL;
将第二个节点的下一个指针设置为第三个分配的节点
current->next = (struct node*) malloc(sizeof(struct node));
将当前前进到第三个节点并设置数据
current = current->next;
current->data = 50;
current->next = NULL;
显示3个节点
struct node *temp = head;
while(temp != NULL){
printf("%d ",temp->data);
temp = temp->next;
}