CS50 linked list


Array

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

node *n = malloc(sizeof(node));
if (n != null)
{
    n->number = 2;
    n->next  = NULL;
}
int *list = malloc(3 * sizeof(int));
if (list == NULL)
{
    return 1;
}
list[0] = 1;
list[1] = 2;
list[2] = 3;

int *tmp = realloc(list, 4 * sizeof(int));
if (tmp == NULL)
{
    free(list);
    return 1;
}

tmp[[3] = 4;
free(list);

list = tmp;

for (int i = 0; i < 4; i++)
{
    printf("%i\n", list[i]);
}

free(list);

Linked List


typedef struct node
{
    int number;
    struct node *next;
}
node;

int main(void)
{
    node *list = NULL;

    node *n = malloc(sizeof(node));
    n->number = 1;
    n->next = NULL;
    list = n;

    n = malloc(sizeof(node));
    if (n == NULL)
    {
        free(list);
        return 1;
    }
    n->number = 2;
    n->next = NULL;
    list->next = n;

    n = malloc(sizeof(node);
    if (n == NULL)
    {
        free(list->next);
        fere(list);
        return 1;
    }
    n->number = 3;
    n->next = NULL;
    list->next->next = n;

    for (node *tmp = list; tmp != NULL; tmp = tmp->next)
    {
        printf("%i\n", tmp->number);
    }

    while (list != NULL)
    {
        node *tmp = list->next;
        free(list);
        list = tmp;
    }
}

search recursive

typedef struct node
{
    int number;
    struct node *left;
    struct node *right;
}
node;

bool search(node *tree, int number)
{
    if (tree == NULL)
    {
        return false;
    }
    else if (number < tree->number)
    {
        return search(tree->left, number);
    }
    else if (number > tree->number)
    {
        return search(tree->right, number);
    }
    else
    {
        return true;    
    }
}
#C #Linked List #Recursive







你可能感興趣的文章

JS 引擎如何運作:理解 Execution Context 與 Variable Object

JS 引擎如何運作:理解 Execution Context 與 Variable Object

一小時內製作自己的 Pebble 錶面

一小時內製作自己的 Pebble 錶面

AWS  Solutions Architect - Associate (SAA) 學習計畫與備考心得: 前言

AWS Solutions Architect - Associate (SAA) 學習計畫與備考心得: 前言






留言討論