在C语言中动态创建单链表
我的程序中有一个名为employee的结构,其定义如下:在C语言中动态创建单链表,c,pointers,struct,linked-list,C,Pointers,Struct,Linked List,我的程序中有一个名为employee的结构,其定义如下: struct employee { int id; int age; struct *employee next; }; 我如何从用户那里获取输入,如何从他们的输入中创建一个结构,如何使用指针创建一个单链接列表?我在弄清楚如何动态地做这件事时遇到了很多问题。在Java中,这很容易通过构造函数实现,但是在C中如何实现呢 编辑:假设输入仅为两个整数(id和年龄)。这就是创建新的员工结构的方式。您正在使用malloc函数动态分配内存 str
struct employee {
int id;
int age;
struct *employee next;
};
我如何从用户那里获取输入,如何从他们的输入中创建一个结构,如何使用指针创建一个单链接列表?我在弄清楚如何动态地做这件事时遇到了很多问题。在Java中,这很容易通过构造函数实现,但是在C中如何实现呢
编辑:假设输入仅为两个整数(id和年龄)。这就是创建新的
员工结构的方式。您正在使用malloc
函数动态分配内存
struct employee *new_employee = (struct employee*)malloc(sizeof(struct employee));
现在,我们需要将数据填入新创建的employee
字段:
new_employee -> id = input_id;
new_employee -> age = input_age;
对于next
指针,它通常被赋予空值。这是为了防止next
指针指向任意内存位置
new_employee -> next = NULL;
最后,我们必须链接列表。为此,您必须将上一个雇员字段的next
指针指向当前雇员字段(例如:如您在注释中所述,第一个(9,3)的下一个指针指向第二个(3,2))
因为它是一个单链表,我们不能回溯。因此,有两种方法可以访问前面的字段
首先是维护指向链接列表最后一个字段的指针
第二种方法是遍历整个列表直到结束,当到达最后一个元素时,更改其next
指针
第二种方法的实施:
node *temp = *start;
if(temp!=NULL)
{
while(temp -> next)
temp = temp -> next;
temp -> next = new_employee;
}
希望有帮助 注意:别给我鱼教我怎么钓鱼
struct node {
int value;
struct *node next;
};
node* aux = (node*) malloc(sizeof(node));
char line[256];
int i;
if (fgets(line, sizeof(line), stdin)) {
if (1 == sscanf(line, "%d", &i)) {
/* i can be safely used */
}
}
/* This will be the unchanging first node */
struct node *root;
/* Now root points to a node struct */
root = (struct node *) malloc( sizeof(struct node) );
/* The node root points to has its next pointer equal to a null pointer
set */
root->next = 0;
/* By using the -> operator, you can modify what the node,
a pointer, (root in this case) points to. */
root->value = 5;
/* This won't change, or we would lose the list in memory */
struct node *root;
/* This will point to each node as it traverses the list */
struct node *conductor;
root = malloc( sizeof(struct node) );
root->next = 0;
root->value = 12;
conductor = root;
if ( conductor != 0 ) {
while ( conductor->next != 0)
{
conductor = conductor->next;
}
}
/* Creates a node at the end of the list */
conductor->next = malloc( sizeof(struct node) );
conductor = conductor->next;
if ( conductor == 0 )
{
printf( "Out of memory" );
return 0;
}
/* initialize the new memory */
conductor->next = 0;
conductor->value = 42;
这是一个例子:
如何动态创建新节点指针?
如何(安全地)获取用户输入?
如何创建链接列表的标题?
如何将新节点添加到链接列表?
现在您必须能够轻松解决问题。
快乐编码:D我写了一篇博客文章,描述了链接列表@karma_geek的实现,这对于我需要做的事情来说有点太复杂了。我是C新手,所以这对我来说仍然是一个挑战。好吧,首先你需要了解动态分配的基础知识-如何使用malloc、free等。另外,你必须知道指针是如何工作的。你的问题很广泛,有什么特别的问题吗?我用scan f来接受两个整数(只要两个整数都不是0),并用它们创建一个结构。我还希望这些结构是一个链表。假设用户输入以下内容:(9,3)和(3,2)。我将创建两个结构,第一个(9,3)具有指向第二个(3,2)的下一个指针。