Create a linked list to store user input number, add new numbers at the end of the list - C Data Structure

C examples for Data Structure:Linked List

Description

Create a linked list to store user input number, add new numbers at the end of the list

Demo Code

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int num;//  ww w. ja v  a2 s. c  o m
    struct node *next;
} Node, *NodePtr;

void printList(NodePtr);
NodePtr makeNode(int);

int main() {
    int n = 1;
    NodePtr top = NULL, np, last;
    
    printf("type a number, 0 to stop:\n");

    while (n != 0) {
        np = makeNode(n);   

        if (top == NULL) 
           top = np;  
        else 
           last -> next = np; //set last -> next for other nodes

        last = np;  //update last to  new node

        printf("type a number, 0 to stop:\n");

        if (scanf("%d", &n) != 1) 
           n = 0;
    }
    printList(top);
}

NodePtr makeNode(int n) {
    NodePtr np = (NodePtr) malloc(sizeof (Node));
    np -> num = n;
    np -> next = NULL;
    return np;
}

void printList(NodePtr np) {
    while (np != NULL) {  // as long as there's a node
        printf("%d\n", np -> num);
        np = np -> next;  // go on to the next node
    }
}

Related Tutorials