【题解】 判断一个链表是否为回文结构
判断一个链表是否为回文结构
题目链接:判断一个链表是否为回文结构
解题思路1:借助数组
遍历链表将值都放在数组中,再遍历数组元素,判断该数组是否为一个回文结构
代码如下:
bool isPail(ListNode* head) {ListNode* cur = head;vector<int> v;while(cur != nullptr){v.push_back(cur->val);cur = cur->next;}for(int i=0,j=v.size()-1; i<j; ++i,--j){if(v[i] != v[j]){return false;}}return true;}
解题思路2:反转部分链表进行对比
注意不能反转全部的链表,否则链表整个结构都改变了,再想和初始的链表进行对比的时候,发现最初的链表已经找不到了,原来的head的next为空了,原来的结构不复存在,所以强调反转部分链表
首先遍历链表,统计链表的长度
将长度除以2,从头节点开始走这么多的位置,找到中间位置
从中间位置开始,对链表进行反转
用双指针一个从头,一个从反转的部分链表的头开始依次比较对应位置的元素值是否相等
代码如下:
ListNode* reverse(ListNode* head){ListNode* res = nullptr;ListNode* pre = nullptr;ListNode* cur = head;while(cur != nullptr){ListNode* temp = cur->next;if(cur->next == nullptr) res = cur;cur->next = pre;pre = cur;cur = temp;}return res;}bool isPail(ListNode* head) {ListNode* p = head;int n = 0;while(p != nullptr){p = p->next;n++;}n = n / 2;p = head;while(n > 0){p = p->next;n--;}p = reverse(p);ListNode* q = head;while(p != nullptr){if(p->val != q->val) return false;p = p->next;q = q->next;}return true;}
解题思路3:利用快慢指针找中点
慢指针每次走一个节点,快指针每次走两个节点,快指针到达链表尾的时候,慢指针刚好走到了链表中点
从中点的位置 ,开始将后半段链表反转
左右双指针,左指针从链表头开始往后遍历,右指针从链表尾往反转后的链表遍历,依次比较遇到的值
代码如下:
ListNode* reverse(ListNode* head){ListNode* res = nullptr;ListNode* pre = nullptr;ListNode* cur = head;while(cur != nullptr){ListNode* temp = cur->next;if(cur->next == nullptr) res = cur;cur->next = pre;pre = cur;cur = temp;}return res;}bool isPail(ListNode* head) {ListNode* slow = head;ListNode* fast = head;//双指针找中点while(fast != nullptr && fast->next != nullptr){slow = slow->next;fast = fast->next->next;}//中点处反转slow = reverse(slow);fast = head;while(slow != nullptr){if(slow->val != fast->val) return false;fast = fast->next;slow = slow->next;} return true;}
解题思路4:栈逆序
将元素放到栈中,再依次取出栈顶元素和链表进行对比,如果都相同,那该链表就是回文链表
bool isPail(ListNode* head) {stack<int> st;ListNode* cur = head;while(cur != nullptr){st.push(cur->val);cur = cur->next;}cur = head;while(!st.empty()){if(cur->val != st.top()) return false;st.pop();cur = cur->next;}return true;}