-
Notifications
You must be signed in to change notification settings - Fork 2
/
13-is_palindrome.c
114 lines (98 loc) · 2 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include "lists.h"
/**
* reverse - reverses the second half of the list
*
* @h_r: head of the second half
* Return: no return
*/
void reverse(listint_t **h_r)
{
listint_t *prv;
listint_t *crr;
listint_t *nxt;
prv = NULL;
crr = *h_r;
while (crr != NULL)
{
nxt = crr->next;
crr->next = prv;
prv = crr;
crr = nxt;
}
*h_r = prv;
}
/**
* compare - compares each int of the list
*
* @h1: head of the first half
* @h2: head of the second half
* Return: 1 if are equals, 0 if not
*/
int compare(listint_t *h1, listint_t *h2)
{
listint_t *tmp1;
listint_t *tmp2;
tmp1 = h1;
tmp2 = h2;
while (tmp1 != NULL && tmp2 != NULL)
{
if (tmp1->n == tmp2->n)
{
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
else
{
return (0);
}
}
if (tmp1 == NULL && tmp2 == NULL)
{
return (1);
}
return (0);
}
/**
* is_palindrome - checks if a singly linked list
* is a palindrome
* @head: pointer to head of list
* Return: 0 if it is not a palindrome,
* 1 if it is a palndrome
*/
int is_palindrome(listint_t **head)
{
listint_t *slow, *fast, *prev_slow;
listint_t *scn_half, *middle;
int isp;
slow = fast = prev_slow = *head;
middle = NULL;
isp = 1;
if (*head != NULL && (*head)->next != NULL)
{
while (fast != NULL && fast->next != NULL)
{
fast = fast->next->next;
prev_slow = slow;
slow = slow->next;
}
if (fast != NULL)
{
middle = slow;
slow = slow->next;
}
scn_half = slow;
prev_slow->next = NULL;
reverse(&scn_half);
isp = compare(*head, scn_half);
if (middle != NULL)
{
prev_slow->next = middle;
middle->next = scn_half;
}
else
{
prev_slow->next = scn_half;
}
}
return (isp);
}