-
Notifications
You must be signed in to change notification settings - Fork 0
/
13-is_palindrome.c
executable file
·67 lines (62 loc) · 1.5 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
#include "lists.h"
/**
* is_palindrome - Checks if a linked list is a palindrome
* @head: pointer to the head node of the list
*
* Return: 1 if the list is a palindrome, 0 if it isn't
*/
int is_palindrome(listint_t **head)
{
listint_t *ptrSlow = *head, *ptrFast = *head, *ptrTemp = *head, *listDuplicated = NULL;
if (*head == NULL || (*head)->next == NULL)
return (1);
while (1)
{
ptrFast = ptrFast->next->next;
if (!ptrFast)
{
listDuplicated = ptrSlow->next;
break;
}
if (!ptrFast->next)
{
listDuplicated = ptrSlow->next->next;
break;
}
ptrSlow = ptrSlow->next;
}
flipLinkedList(&listDuplicated);
while (listDuplicated && ptrTemp)
{
if (ptrTemp->n == listDuplicated->n)
{
listDuplicated = listDuplicated->next;
ptrTemp = ptrTemp->next;
}
else
return (0);
}
if (!listDuplicated)
return (1);
return (0);
}
/**
* flipLinkedList - Flips the linked list
* @head: pointer to the head node of the list
*
* Return: pointer to the head node of the flipped list
*/
void flipLinkedList(listint_t **head)
{
listint_t *nodePrev = NULL;
listint_t *nodeCurr = *head;
listint_t *nextNode = NULL;
while (nodeCurr)
{
nextNode = nodeCurr->next;
nodeCurr->next = nodePrev;
nodePrev = nodeCurr;
nodeCurr = nextNode;
}
*head = nodePrev;
}