-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path13-is_palindrome.c
71 lines (61 loc) · 1.08 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
67
68
69
70
71
#include "lists.h"
/**
* reverse_listint - reverses a linked list
* @head: pointer to the first node in the list
* Return: pointer to the first node in the new list
*/
void reverse_listint(listint_t **head)
{
listint_t *prev = NULL;
listint_t *current = *head;
listint_t *next = NULL;
while (current)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
/**
* is_palindrome - checks if a linked list is a palindrome
* @head: double pointer to the linked list
*
* Return: 1 if it is, 0 if not
*/
int is_palindrome(listint_t **head)
{
listint_t *slow = *head, *fast = *head, *temp = *head, *dup = NULL;
if (*head == NULL || (*head)->next == NULL)
return (1);
while (1)
{
fast = fast->next->next;
if (!fast)
{
dup = slow->next;
break;
}
if (!fast->next)
{
dup = slow->next->next;
break;
}
slow = slow->next;
}
reverse_listint(&dup);
while (dup && temp)
{
if (temp->n == dup->n)
{
dup = dup->next;
temp = temp->next;
}
else
return (0);
}
if (!dup)
return (1);
return (0);
}