I am teaching myself C and have a couple books on the subject. I am totally at a loss for exactly what this exercise is asking for.
Code:
// Write a function called insertEntry() to insert 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 this chapter), and a pointer to an element in
the list after which the new entry is to be inserted.
// The function dveloped in exercise 2 only inserts an element after an existing element in the list,
thereby prenting you from inserting a new entry at the front of the list.
How can you use this same function and yet overcome this problem?
(Hint: Think about setting up a special structure to point to the beginning of the list.)
#include <stdio.h>
struct entry1
{
int value;
struct entry1 *next;
};
struct entry1 n0, n1, n2, n3, nInsert,
*insert = &nInsert,
*after = &n3,
*list_pointer = &n1;
void insertEntry(struct entry1 *insert, struct entry1 *after)
{
if (after->next == &n1) {
insert->next = &n2;
list_pointer = insert;
}
insert->next = after->next;
after->next = insert;
}
int main (void)
{
n1.value = 100;
n2.value = 200;
n3.value = 300;
nInsert.value = 20;
n0.next = &n1;
n1.next = &n2;
n2.next = &n3;
n3.next = (struct entry1 *) 0;
insertEntry(insert, &n0);
while (list_pointer != (struct entry1 *) 0) {
printf("%i\n", list_pointer->value);
list_pointer = list_pointer->next;
}
return 0;
}
This is a working version of the exercise, but I don't think I'm doing what's asked. I was able to add an element to the beginning of the list using an if statement, not creating a special structure that points to the beginning of the list.
How would I go about creating a special structure that points to the beginning of the list to add a new element at the beginning of the list?
Thank you for your help.