-
Notifications
You must be signed in to change notification settings - Fork 0
/
234. Palindrome Linked List.c
76 lines (69 loc) · 1.85 KB
/
234. Palindrome Linked List.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
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
struct ListNode *left = head, *middle = head->next, *right = middle->next;
left->next = NULL;
while(right != NULL) {
middle->next = left;
left = middle;
middle = right;
right = right->next;
}
middle->next = left;
return middle;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
// bool isPalindrome(struct ListNode* head) {
// if (head == NULL || head->next == NULL) {
// return true;
// }
// struct ListNode *left = head, *right = head;
// int len = 0;
// while (right) {
// right = right->next;
// len++;
// }
// struct ListNode *temp = head;
// for (int i = 0; i < len / 2; i++) {
// temp = temp->next;
// }
// right = reverseList(len % 2 > 0 ? temp->next : temp);
// temp->next = NULL;
// while (right != NULL) {
// if (left->val != right->val) {
// return false;
// }
// left = left->next;
// right = right->next;
// }
// return true;
// }
bool isPalindrome(struct ListNode* head) {
struct ListNode *fast = head, *slow = head, *temp = NULL;
while (fast) {//¿ìÂýÖ¸ÕëÕÒµ½Á´±íÖеã
slow = slow->next;
fast = fast->next ? fast->next->next : fast->next;
}
while (slow) {
fast = slow->next;
slow->next = temp;
temp = slow;
slow = fast;
}
fast = head;
slow = temp;
while (fast && slow) {
if (fast->val != slow->val)
return false;
fast = fast->next;
slow = slow->next;
}
return true;
}