-
Notifications
You must be signed in to change notification settings - Fork 0
/
13-insert_number.c
51 lines (47 loc) · 1.01 KB
/
13-insert_number.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "lists.h"
#include <stdlib.h>
/**
* insert_node - Inserts a number into a sorted singly linked list
* @head: The head of the sorted singly linked list
* @number: The number to inserts in the singly linked list
*
* Return: The singly linked list with the new number added
*/
listint_t *insert_node(listint_t **head, int number)
{
listint_t *current = NULL, *new_node = NULL, *temp = NULL;
new_node = malloc(sizeof(listint_t));
if (new_node == NULL)
return (NULL);
new_node->n = number;
if (*head)
{
current = *head;
if (number <= current->n)
{
new_node->next = current;
*head = new_node;
}
else
{
while (current->next)
{
if (number <= current->next->n)
{
temp = current->next;
current->next = new_node;
new_node->next = temp;
return (*head);
}
current = current->next;
}
temp = current->next;
current->next = new_node;
new_node->next = temp;
}
return (*head);
}
new_node->next = NULL;
*head = new_node;
return (*head);
}