Insert new element to a linked list by order - C Data Structure

C examples for Data Structure:Linked List

Description

Insert new element to a linked list by order

Demo Code

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

typedef struct node {
    int num;//from  w w w  . j  a  v a  2 s  .  c  o  m
    struct node *next;
} Node, *NodePtr;

void printList(NodePtr);
NodePtr addInPlace(NodePtr, int);

int main() {

    int n = 1;
    NodePtr top = NULL;
    
    while (n != 0) {
        top = addInPlace(top, n);
        printf("type a number, 0 to stop:\n");
        if (scanf("%d", &n) != 1) 
           n = 0;
    }
    printList(top);
}

NodePtr addInPlace(NodePtr top, int n) {
    NodePtr np, curr, prev, makeNode(int);

    np = makeNode(n);

    prev = NULL;

    curr = top;

    while (curr != NULL && n > curr -> num) {
        prev = curr;
        curr = curr -> next;
    }

    if (prev == NULL) { //new number must be added at the top
        np -> next = top;
        return np; //the top of the list has changed to the new node
    }
    np -> next = curr;
    prev -> next = np;
    return top; //the top of the list has not changed
}

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