leetcode 234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
判断一个链表是不是回文的。
思路:遍历节点得到总数tot,然后反转链表的后半部分,再和前半部分比较。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* head2 = nullptr;
int tot = 0;
int num = 0;
void reverse(ListNode* p, ListNode* q) {
if (p == nullptr) {
head2 = q;
return ;
}
reverse(p->next, p);
if (q) q->next = nullptr;
if (p) p->next = q;
}
bool isPalindrome(ListNode* head) {
ListNode* p = head;
ListNode* x = nullptr;
ListNode* q = nullptr;
while (p) {
tot++;
p = p->next;
}
p = head;
while (p) {
num++;
if (num == tot/2) {
x = p;
break;
}
p = p->next;
}
reverse(x, nullptr);
p = head;
q = head2;
while (p && q) {
if (p->val != q->val) return false;
p = p->next;
q = q->next;
}
return true;
}
};
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: