The problem is that every time the function addNodePos
is being called head
pointer is NULL
(saw that in debugger), and it just creates a list of one node, which points to itself as it is a circular doubly-linked list. And it displays "List is empty." because list
is also NULL
, when passing to a printList
function. Have been trying to understand why but still there is no result.
Here is the code (removed excessive code according to SSCCE)
#include <stdio.h>
#include <stdlib.h>
struct DoubleList
{
int id;
struct DoubleList *next;
struct DoubleList *prev;
};
void addNodePos(struct DoubleList* head, int value, int position);
void printList (struct DoubleList* head);
//void clearList (struct DoubleList* head);
int main()
{
int value, position;
struct DoubleList *list = NULL;
printf("\nvalue: ");
scanf("%x", &value);
printf("position: ");
scanf("%d", &position);
addNodePos(list, value, position);
printf("\nvalue: ");
scanf("%x", &value);
printf("position: ");
scanf("%d", &position);
addNodePos(list, value, position);
printList(list);
//clearList(list);
return 0;
}
void addNodePos(struct DoubleList* head, int value, int position)
{
int i;
struct DoubleList *node;
if ( (node = malloc (sizeof(struct DoubleList))) != NULL ){
node->id=value;
if (head==NULL) {
// points to itself as it is the only node in a list
node->next=node;
node->prev=node;
head=node;
} else {
struct DoubleList *current=head;
for (i = position; i > 1; i--)
current=current->next;
// reassign pointers -- relink nodes
current->prev->next=node;
node->prev=current->prev;
node->next=current;
current->prev=node;
}
}
printf("Element has been added.\n\n");
}
void printList(struct DoubleList* head)
{
if (head==NULL)
printf("\nList is empty.\n\n");
else {
struct DoubleList *current=head;
printf("\nThe list: ");
do {
printf("%d", current->id);
current=current->next;
if(current != head)
printf("<->");
} while(current!=head);
printf("\n\n");
}
}