Skip to main content
edited title
Link
200_success
  • 145.7k
  • 22
  • 191
  • 481

Exercise to create an insertString function to linked-list. Seems too simple. Am I missing something?

Source Link
gloopit
  • 143
  • 3

Exercise to create an insertString function to linked-list. Seems too simple. Am I missing something?

Working from 'Programming in C' by Kochan. I'm on an exercise in the chapter 'Pointers'.

This was the exercise:

'Write a function called insertEntry() to inset a new entry into a linked list. Have the procedure take as arguments a pointer to the list entry to be inserted (of type struct entry as defined in chapter), and a pointer to an element after which the new entry is to be inserted.

I've been struggling through this book but this exercise only took me a few minutes, I'm concerned I'm missing the point. Can you please make some suggestions regarding if I've gone wrong?

It compiles and runs fine.

Could I have done this better?

#include <stdio.h>

struct entry
    {
        int value;
        struct entry *next;
    };

void insertEntry(struct entry *addOn, struct entry *element);

int main (void)
{
    
    
    struct entry n1, n2, n3, addOn;
    struct entry *list_pointer = &n1;
    
    n1.value = 100;
    n1.next = &n2;
    
    n2.value = 200;
    n2.next = &n3;
    
    n3.value = 300;
    n3.next = (struct entry *) 0;
    
    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }
    
    list_pointer = &n1;
    insertEntry(&addOn, &n3);
    
    while(list_pointer != (struct entry *) 0)
    {
        printf("%i\n", list_pointer->value);
        list_pointer = list_pointer->next;
    }
    
    return 0;
}

void insertEntry(struct entry *addOn, struct entry *element)
{
    element->next = addOn;
    addOn->value = 400;
    addOn->next = (struct entry *) 0;
}