Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 11 additions & 14 deletions lists.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,20 @@ Node *head = NULL;
// add a node to the list
Node *addNode(int data)
{
Node *new = NULL;
// allocate the new node
Node *new = malloc(sizeof(Node));
if (new == NULL)
return NULL;

// two cases:

// if the list is empty.
if (head == NULL)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case of head being null, wouldn't doing new->next = NULL the same as new->next = head ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Insert have error. If cueernt is NULL, empty list, you try to do current->next on Null Pointer.

{
new = malloc(sizeof(Node));
if (new == NULL)
return NULL;

new->data = data;
head = new;
new->next = NULL;
} else {
new = malloc(sizeof(Node));
if (new == NULL)
return NULL;

new->data = data;
new->next = head;
head = new;
Expand All @@ -52,10 +48,10 @@ int removeNode(int data)
head = current->next;
} else {
prev->next = current->next;
free(current);
current = NULL;
}

// deallocate the current node
free(current);
current = NULL;
return 1;
}
prev = current;
Expand All @@ -69,9 +65,10 @@ int removeNode(int data)
Node *insertNode(int data, int position)
{
Node *current = head;
while (current != NULL && position != 0)
while (current->next != NULL && position != 0)
{
position--;
current = current->next;
}

if (position != 0)
Expand Down Expand Up @@ -168,4 +165,4 @@ int main(int argc, char **argv)


return 0;
}
}