I'm trying to get into C, and I was wondering if I messed up regarding correctly implementing a linked list.
node.h
typedef struct node
{
int n;
struct node* next;
}node;
code
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// struct for linked lists
#include "node.h"
bool searchLinked(node* list, int* value);
void insertLinked(node* list, int* value);
void initList(node* list);
void printList(node* list);
/*This small program shows how to utilize the data structure linked lists*/
/*and append, search and delete data in them*/
int main(int argc, char* argv[])
{
// nodes
node* root = malloc(sizeof(node));
// initilize the list and add dummy values
initList(root);
// print the list
printList(root);
// search the list for our value, if not found we try to add it
int value = 1;
if (!searchLinked(root, &value))
{
insertLinked(root, &value);
}
free(root);
return 1;
}
void initList(node* list)
{
list->n = 4;
list->next = malloc (sizeof(node));
// second node access
list = list->next;
list->n = 3;
list->next = malloc (sizeof(node));
// third node
list = list->next;
list->n = 2;
// set this to NULL since this is last node
list->next = NULL;
}
// method used to traverse and search our list
bool searchLinked(node* list, int* value)
{
node* cond = malloc(sizeof(node));
cond = list;
while (cond != NULL)
{
if (cond->n == *value)
{
free(cond);
return true;
}
else
{
cond = cond->next;
}
}
free(cond);
return false;
}
void printList (node* list)
{
node* cond = malloc(sizeof(node));
cond = list;
for (int i = 0; cond != NULL; i++)
{
printf("The root no: %d has the data: %d\n", i, cond->n);
cond = cond->next;
}
free(cond);
}
// this method is used when we want to append data to the last element in the list
// please note that if we were to add it to the start of the list then we would need to
// make sure that we dont drop the list by dissconnecting the 2nd member
void insertLinked(node* list, int* value)
{
node* cond = malloc(sizeof(node));
cond = list;
while (cond != NULL)
{
if (cond->next == NULL)
{
// assign the last node the adress of the new node
cond->next = malloc(sizeof(node));
// assign the last node to the newly new node
cond = cond->next;
// assign the values for the last (new) node
cond->n = *value;
cond->next = NULL;
// try to access the next one, which should be null which will break the loop
cond = cond->next;
}
else
{
cond = cond->next;
}
}
free(cond);
}
insertLinked
function actually just adds the node to the end of a heap variable that is destroyed. Did you mean to actually insert the nodes such that they are in sequential order (i.e.1->2->3->..
), or merely just insert them at the end if the value isn't found? – txtechhelp yesterdaycond = list;
ininsertLinked
leaks thenode
you allocated on the previous line. You probably meant*cond = *list;
. – zenith 14 hours ago