-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13-is_palindrome.c
66 lines (59 loc) · 1.14 KB
/
13-is_palindrome.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "lists.h"
/**
* is_palindrome - a function checks if a singly linked list is a palindrome.
*
* @head: head of the singly linked list.
*
* Return: 0 if it is not a palindrome, 1 if it is a palindrome.
*/
int is_palindrome(listint_t **head)
{
listint_t *slow = *head, *fast = *head, *temp = *head, *reversed = NULL;
if (head == NULL || *head == NULL || (*head)->next == NULL)
return (1);
while (1)
{
reversed = fast->next;
fast = fast->next->next;
slow = slow->next;
if (fast == NULL)
{
reversed_list(&slow);
break;
}
if (fast->next == NULL)
{
reversed_list(&slow->next);
reversed = fast;
break;
}
}
while (reversed != NULL)
{
if (reversed->n != temp->n)
return (0);
temp = temp->next;
reversed = reversed->next;
}
return (1);
}
/**
* reversed_list - reverse a singly linked list.
*
* @head: head of a linked list.
*
* Return: numbers.
*/
void reversed_list(listint_t **head)
{
listint_t *current = *head;
listint_t *previous = NULL;
listint_t *next = NULL;
while (current != NULL)
{
next = current->next;
current->next = previous;
previous = current;
current = next;
}
}