Hi all,
Just having a few dramas with doubly linked lists. I am just trying to write an insert function with the following structures. The insert function does not have to insert the data into a sorted list, so basically it can just add another node to the end of a list.
The trouble I am having is that I figure I can use a for loop to loop through the list until I find the last node.. but my logic is not right. Can anyone make some suggestions?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#define MAX 50 // The maximum size of the arrays in the struct
typedef struct list DLL;
typedef struct node NODE;
struct node
{
void *data;
NODE *prior;
NODE *next;
};
struct list
{
long int count;
NODE *head;
NODE *tail;
};
typedef struct
{
long int id;
char name[MAX];
char address[MAX];
float salary;
} PERSON;
typedef struct
{
PERSON details;
char department[MAX];
char position[MAX];
} EMPLOYEE;
void init_list(DLL *);
int insert(DLL *, void*, size_t);
int main(void)
{
DLL *pMylist;
EMPLOYEE *pEmployees;
if ((pMylist = (DLL *) malloc (sizeof(DLL))) == NULL)
{
printf("Error: Unable to allocate memory");
exit(1);
}
if ((pEmployees = (EMPLOYEE *) malloc (sizeof(EMPLOYEE))) == NULL)
{
printf("Error: Unable to allocate memory");
exit(1);
}
init_list (pMylist);
printf("Enter a number: ");
while (pEmployees->details.id != 999)
{
scanf("%d", &pEmployees->details.id);
insert(pMylist, pEmployees, sizeof(EMPLOYEE));
printf("Enter a number: ");
}
free (pMylist);
free (pEmployees);
return EXIT_SUCCESS;
}
// The function with all the dramas :)
int insert(DLL *pRoot, void *pData, size_t size)
{
NODE *pNewnode;
NODE *pThis;
NODE *pNext;
// Allocate memory for a new node in the list
if ((pNewnode = (NODE *) malloc(sizeof(NODE))) == NULL)
{
printf("Error: Unable to allocate memory for pNewnode");
exit(EXIT_FAILURE);
}
// Allocate memory for the input from user
if ((pNewnode->data = malloc(size)) == NULL)
{
printf("Error: Unable to allocate memory for pNewnode->data");
exit(EXIT_FAILURE);
}
// Copy user input to node
memcpy(pNewnode->data, pData, size);
// If the first node
if (pRoot->head == NULL)
{
printf("this is the start of a beautiful list");
pRoot->head = pNewnode;
return 1;
}
else
{
// This loop is erroneous
for (pThis = (pRoot->head); (pNext = pThis->next) != NULL; pThis = pNext)
{
// Insert next in list
}
}
return 1;
}
void init_list(DLL *pMylist)
{
pMylist->count = (long) NULL;
pMylist->head = NULL;
pMylist->tail = NULL;
}
This is not the final code obviously, it is a test program to demonstrate the issues that I am having so there could be some other unusual things happening in this code