As mentioned I don't seem to be able to understand the error in my code, what is it that I'm doing wrong in this particular piece of code:
The Node is written as such:
struct Node {
int data;
struct Node *link;
};
This is the append to the beginning:
void Shift(struct Node **head, int new_data) {
struct Node *New;
New = (struct Node *)malloc(sizeof(struct Node));
if (New == NULL) {
printf("It is Null\n");
}
New->data = new_data;
New->link = head;
}
This is the append to the end:
void Shift(struct Node *head, int new_data) {
while (head != NULL) {
head = head->link;
}
struct Node *New;
New = (struct Node *)malloc(sizeof(struct Node));
if (New == NULL) {
printf("It is Null\n");
}
New->link = NULL;
New->data = new_data;
If anyone knows what's up, please tell me what to add and why. Thanks in advance!!
I've looked it up and it said that I had to do head->link = new, but it results in a never ending cascade of number...
There are multiple problems:
you do not return if memory allocation fails.
the first version (inserting at the beginning of the list) does not handle
headproperly: it is a pointer to the head node pointer of the list soNew->linkmust be set to*headand*headmust be updated to become the new head:*head = New;.the second version skips the nodes until
headis a null pointer, causing undefined behavior if you link the new node as itsnextnode. You should instead loop until you have the last node of the list and link theNewnode as itsnextnode.the second version should also take a double pointer
struct Node **headso the head of the list can be updated if the list was empty.Here are modified versions:
The
Appendfunction can be simplified into this more compact version that may be more difficult to understand: