Skip to content

Commit 6e51a72

Browse files
committed
Implement add_dnodeint_end function to insert a new node at the end
Created a new node and linked it appropriately Handled memory allocation failure gracefully Handled both empty and non-empty lists Updated the prev and next pointers accordingly Added proper documentation and comments
1 parent 638a3c1 commit 6e51a72

File tree

3 files changed

+64
-0
lines changed

3 files changed

+64
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include "lists.h"
2+
3+
/**
4+
* add_dnodeint_end - Adds a new node at the end of a dlistint_t list.
5+
* @head: Double pointer to the head of the list.
6+
* @n: Value to be stored in the new node.
7+
*
8+
* Return: Address of the new element, or NULL if it failed.
9+
*/
10+
11+
dlistint_t *add_dnodeint_end(dlistint_t **head, const int n)
12+
{
13+
dlistint_t *new, *temp;
14+
15+
new = malloc(sizeof(dlistint_t));
16+
if (!new)
17+
{
18+
return (NULL);
19+
}
20+
new->n = n;
21+
new->next = NULL;
22+
temp = *head;
23+
/* Empty list, new node becomes the head */
24+
if (!temp)
25+
{
26+
new->prev = NULL;
27+
*head = new;
28+
return (new);
29+
}
30+
while (temp->next)
31+
{
32+
temp = temp->next;
33+
}
34+
/* Insert new node at the end of the list */
35+
temp->next = new;
36+
new->prev = temp;
37+
return (new);
38+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
#include <stdlib.h>
2+
#include <string.h>
3+
#include <stdio.h>
4+
#include "lists.h"
5+
6+
/**
7+
* main - check the code
8+
*
9+
* Return: Always EXIT_SUCCESS.
10+
*/
11+
int main(void)
12+
{
13+
dlistint_t *head;
14+
15+
head = NULL;
16+
add_dnodeint_end(&head, 0);
17+
add_dnodeint_end(&head, 1);
18+
add_dnodeint_end(&head, 2);
19+
add_dnodeint_end(&head, 3);
20+
add_dnodeint_end(&head, 4);
21+
add_dnodeint_end(&head, 98);
22+
add_dnodeint_end(&head, 402);
23+
add_dnodeint_end(&head, 1024);
24+
print_dlistint(head);
25+
return (EXIT_SUCCESS);
26+
}

β€Ž0x17-doubly_linked_lists/dβ€Ž

16.6 KB
Binary file not shown.

0 commit comments

Comments
Β (0)