COMS 3157 Advanced Programming

Index of 2024-1/code/10

Parent directory
two-nodes.c

two-nodes.c

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

struct Node {
    struct Node *next;
    int val;
};

struct Node *create2Nodes(int x, int y)
{
    struct Node *n2 = malloc(sizeof(struct Node));
    if (!n2) {
        return NULL;
    }
    n2->val = y;
    n2->next = NULL;

    struct Node *n1 = malloc(sizeof(struct Node));
    if (!n1) {
        free(n2);    // don't forget to free the node we already allocated
        return NULL;
    }
    n1->val = x;
    n1->next = n2;  // n1 --> n2 --> NULL
    return n1;
}

int main()
{
    struct Node *head = create2Nodes(10, 20);
    if (head == NULL) {
        exit(1);
    }

    //         +----+   +----+----+   +----+----+
    //   head: |  --|-->| 10 |  --|-->| 20 |NULL|
    //         +----+   +----+----+   +----+----+

    printf("%d --> %d\n", head->val, head->next->val);

    free(head->next);  // must free the last node first
    free(head);
}