这里是新手 C 程序员,假设我有一个节点结构如下
struct node{
int data;
struct node *next;
};
如何使用循环创建一个链表,其中第一个节点的数据为 0,并指向下一个节点的数据为 1 的指针。等等
编辑:
int main(int argc, char* argv[]){
struct node a;
a.data = 0;
struct node * tempnode = &a;
for (int i = 1; i < 5; i++){
struct node * next;
next->data = i;
tempnode->next = next;
tempnode = next;
}
这是我尝试过的,但不起作用
最佳答案
这可能会有所帮助..
#include<stdio.h>
#include<stdlib.h>
// Prototypes
void InitList(struct list *sList);
void push(struct list *sList, int data);
void pop(struct list *sList);
void print(struct list *sList);
/* Node Structure */
struct node {
int data;
struct node *next;
};
/* List Structure */
struct list {
struct node *start;
};
int main(int argc, char** argv)
{
int x;
struct list MyList;
InitList(&MyList);
for(x = 0; x < 100; x++) push(&MyList, x);
print(&MyList);
printf("\n");
for(x = 0; x < 25; x++) pop(&MyList);
print(&MyList);
printf("\n");
for(x = 0; x < 80; x++) pop(&MyList);
print(&MyList);
printf("\n");
return 0;
}
/* Initializes the list structure */
void InitList(struct list *sList)
{
sList->start = NULL;
}
/* Adds a value to the front of the list */
void push(struct list *sList, int data)
{
struct node *p;
p = malloc(sizeof(struct node));
p->data = data;
p->next = sList->start;
sList->start = p;
}
/* Prints the list */
void print(struct list *sList)
{
struct node *p = sList->start;
while(p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
/* Removes the first value of the list */
void pop(struct list *sList)
{
if(sList->start != NULL) {
struct node *p = sList->start;
sList->start = sList->start->next;
free(p);
}
}
关于c - 使用for循环创建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21662332/