Using a for loop to create a linked list

18,266

This might help..

#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);
    }
}
Share:
18,266
user2917692
Author by

user2917692

Updated on June 04, 2022

Comments

  • user2917692
    user2917692 almost 2 years

    Newb C programmer here, assuming I have a struct for a node as follows

    struct node{
    
        int data;
        struct node *next;
    
    };
    

    How would I use a loop to make a linked list where the first node's data is 0, and a pointer to the next node whose data is 1. etc.

    EDIT:

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

    Heres what i tried but it doesn't work