使用for循环创建链接列表

时间:2014-02-09 17:22:30

标签: c loops linked-list

Newb 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;
}

继承人我试过但它不起作用

2 个答案:

答案 0 :(得分:3)

这可能会有所帮助..

#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);
    }
}

答案 1 :(得分:1)

您没有分配内存来存储结构数据。这是你如何做到的

for(int i = 1; i < 5; i++) {
    struct node *next = malloc(sizeof *next); // allocate memory to store the struct
    next->data = i;
    tempnode->next = next;
    tempnode = next;
}