这是我正在处理的链表,并试图弄清楚每一行的作用。我学习编程的方式似乎非常困难,而且我感到非常沮丧。无论如何,我理解链接列表是如何工作的,但我不理解代码在说什么以及它究竟在做什么来创建结构。例如:我不明白为什么要将指针分配给节点(13 和 14),尤其是当我对指针的理解是它们用于存储内存位置时。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct numnode
{
int val;
struct numnode * next;
};
typedef struct numnode node;
main()
{
int i;
node * head;
node * newnode;
head = NULL;
for (i = 1; i <= 10; i++)
{
newnode = (node *) malloc(sizeof(node));
newnode->val = i;
newnode->next = NULL;
if (head == NULL)
{
head = newnode;
}
else
{
newnode->next = head;
head = newnode;
}
}
}
最佳答案
这里有一些注释(和一些小的修改以减少代码量)。
/* Linked list node definition */
struct node {
int val;
struct node * next;
};
int main() {
int i;
struct node *head, *new_node;
head = NULL;
for (i = 1; i <= 10; i++) {
// Allocate a new node and initialize its components (val and next)
new_node = (struct node *) malloc(sizeof(node));
new_node->val = i;
new_node->next = NULL;
// The if block is actually not necessary...
if (head == NULL) {
// If the linked list is empty, set the head pointer to the initial node
head = new_node;
} else {
// Now that you have your new node, connect it. Start:
// head->[current linked list]
// [new_node.next]->NULL
new_node->next = head;
// head->[current linked list]->...
// [new_node.next]->[current linked list]->...
head = newnode;
// head->[new_node.next]->[current linked list]->...
}
}
}
关键是 malloc
返回一个指向内存的指针。每个新节点都是动态分配的,因此是内存中的一个位置(不是基本类型)。
关于c - 这个链表程序中每一行的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20508902/