回文链表
用到了之前学到的知识,先用快慢指针分割链表,然后反转第二段链表,将前一段链表与这一段链表的值一个一个相比,如果不同直接return false,否则继续遍历,直到遍历完其中一个链表,return true
判端条件:while(head1 && head2)
这道题真的是折磨,写了这么久的链表,被这道题给整不会了,花了半个小时,不停的写函数,调用函数,太离谱了,这真的是简单题
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
//反转链表的函数
ListNode* reverse(ListNode* head) {
//反转这段链表
ListNode* temp = nullptr;
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur) {
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
//计算链表大小的函数
int sizeofList(ListNode* head) {
int size = 0;
while(head) {
size++;
head = head->next;
}
return size;
}
//判断链表是否是回文链表
bool isPalindrome(ListNode* head) {
int size = sizeofList(head);
if(size == 0 || size == 1) {
return true;
}
ListNode* slow = head;
ListNode* fast = head;
//找到中间节点,并断开
ListNode* brk = nullptr;
while(fast && fast->next) {
fast = fast->next->next;
if(fast == nullptr || fast->next == nullptr) {
brk = slow;
}
slow = slow->next;
}
brk->next = nullptr;
ListNode* head1 = head;
ListNode* head2 = reverse(slow);
while(head1 && head2) {
if(head1->val != head2->val) {
return false;
}else {
head1 = head1->next;
head2 = head2->next;
}
}
return true;
}
};