I’m creating a linked list data structure in C. However, I’m receiving some weird behavior in my implementation of an addLast function. It seems that the added element doesn’t appear until my next call to addLast. My code (I’ll explain through inline comments how I think my code is working):
Helper code:
typedef struct LinkedList linkedlist;
typedef int ListElement;
struct LinkedList{
ListElement data;
linkedlist *next;
};
//Initializes a list;
void CreateList(linkedlist *list, ListElement contents){
list->data = contents;
list->next = NULL;
}
//Prints the items of the list, head first.
void displayList(linkedlist *list){
printf("(%d", list->data);
linkedlist *node = list->next;
if(node == NULL){
}
else{
while(node->next != NULL){
printf(" %d", node->data);
node = node->next;
}
}
printf(")");
}
Problematic code:
//Adds an element at the tail of the list
void addLast(linkedlist *list, ListElement forAdding){
linkedlist *node = list;
linkedlist *NewNode = (linkedlist *) malloc(sizeof(linkedlist));
//Go to the last element in the list
while(node->next != NULL){
node = node->next;
}
//Prepare the node we will add
NewNode->data = forAdding;
NewNode->next = NULL;
//Since node is pointing to the tail element, set its
//next to the NewNode---the new tail
node->next = NewNode;
}
//Special attention to this function!
void List(ListElement items[], linkedlist *list, int numItems){
int i = 0;
while(i < numItems){
addLast(list, items[i]);
printf("Before ");
displayList(list);
printf("\n");
printf("Added %d", items[i]);
displayList(list);
printf("\n");
i++;
}
}
Main function:
int main(){
linkedlist *l= (linkedlist *) malloc(sizeof(linkedlist));
CreateList(l, 0);
int a_list[5] = {1, 2, 3, 5, 6};
List(a_list, l, sizeof(a_list)/sizeof(a_list[0]));
printf("A list of five elements: %d", sizeof(a_list)/sizeof(a_list[0]));
displayList(l);
removeLast(l);
addLast(l, 7);
printf("\nAdded something at last position: ");
displayList(l);
printf("\n");
}
For which I get the output:
Before (0)
Added 1(0)
Before (0)
Added 2(0 1)
Before (0 1)
Added 3(0 1 2)
Before (0 1 2)
Added 5(0 1 2 3)
Before (0 1 2 3)
Added 6(0 1 2 3 5)
A list of five elements: 5(0 1 2 3 5)
Added something at last position: (0 1 2 3 5 6)
As you see, it seems that the item added will only appear on my next call to addLast.
I’ve so far figured out that it is actually there though for some reason it won’t get printed. If, for instance, I do another addLast(list, 6); call just before I close function List (but outside the loop, of course!), the output line Added something at last position... (which happens after a call to addLast(l, 7); will actually display Added something at last position: (0 1 2 3 5 6 6).
So, what am I doing wrong?
Thanks!
The problem is not in
AddLast()it is simply yourdisplayList()function :). You stop printing 1 element before the last element.Change the
displayList()function like that:This function can print empty lists too.