Hi all -
I'm poking around with doing a few Haskell-like functions for linked-lists. Take, drop and so on.
I've done the code below. The problem is that it mysteriously inserts a 0 at the start of the list, and I have no idea why. So - hopefully someone can help out here.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
/* List functions. */
struct node {
int data;
struct node *next;
} ;
/* Function to add data to end of a list */
struct node *list_append(struct node *n, int data)
{
/* A pointer to iterate along the list */
struct node *ptr = NULL;
/* Now, create a new node using the data. */
struct node *newnode = NULL;
newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = NULL;
/* Is our existing list null? */
/* If so, our "list" is just the newly-created node. */
if(n == NULL)
{
n = newnode;
}
else
{
for( ptr = n; ptr->next != NULL; ptr = ptr->next )
{
/* Iterate through the list until we find the last node */
}
/* Add the new node to the end of the list. */
/* In other words: the last ptr->next WAS null, but it is */
/* now pointing to newnode. */
ptr->next = newnode;
}
return n;
} /* End of list_append */
/* Free the list memory. */
void free_list(struct node *n)
{
/* We create TWO pointers. */
/* ptr is used to iterate through the list. */
/* tmp (which points to the same place) is used to */
/* actually free the memory. */
struct node *ptr, *tmp = NULL;
/* Check that the list is non-null. */
if(n != NULL)
{
for( ptr = n; ptr->next != NULL; ptr = ptr->next )
{
/* Iterate through the list */
printf( "Freeing %d\n", (ptr->data) );
tmp = ptr;
free(tmp);
}
/* Free the last element of the list */
/* (where ptr->next IS null). */
printf( "Freeing %d\n", (ptr->data) );
free(ptr);
}
}
void print_list(struct node *n)
{
/* A pointer for iterating. */
struct node *ptr = NULL;
/* Iterate along the list. */
for( ptr = n; ptr->next != NULL; ptr = ptr->next )
{
printf( "mylist->data = %d\n", (ptr->data) );
}
/* For the last nore (where ->next IS NULL), we need to print */
/* it outside the loop. */
printf( "mylist->data = %d\n", (ptr->data) );
}
struct node *take(struct node *n, int i)
{
struct node *ret = NULL;
ret = malloc(sizeof(struct node));
/* A pointer for iterating. */
struct node *ptr = NULL;
int j=0;
for( ptr = n; ( ptr->next != NULL && j < i ); ptr = ptr->next )
{
list_append(ret, ptr->data) ;
/* memcpy( (int *)ret->data, (int *)ptr->data, sizeof( (int *)ptr->data) ); */
j++;
}
return ret;
}
int main()
{
struct node *mynode = NULL;
mynode = list_append(mynode, 23) ;
mynode = list_append(mynode, 45) ;
mynode = list_append(mynode, 71) ;
mynode = list_append(mynode, 248) ;
mynode = list_append(mynode, 18) ;
struct node *mynode2 = NULL;
mynode2 = take(mynode, 3);
print_list(mynode);
puts("Now the new list \n");
print_list(mynode2);
free_list(mynode);
free_list(mynode2);
return 0;
}
Many thanks in advance for your help!
Bye for now -
- latte123