234. 回文链表
知识点:贪心、指针
时间:2020年10月22日
题目链接:https://leetcode-cn.com/problems/palindrome-linked-list/
题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法
- 与Leetcode刷题笔记 143. 重排链表类似
- 找到原链表的中点 快慢指针
- 右半边链表逆序
- 两个链表比较
代码
#include <stdio.h>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* getMidNode(ListNode * head){
ListNode* slow = head;
ListNode* fast = head;
while(fast->next!=nullptr&&fast->next->next!=nullptr){
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverseNode(ListNode* head){
ListNode* pre = nullptr;
ListNode* cur = head;
while(cur!=nullptr){
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head==nullptr){return 1;}
ListNode* midnode = getMidNode(head);
ListNode* reverse = reverseNode(midnode->next);
ListNode* tmp1 = head;
ListNode* tmp2 = reverse;
while(tmp2 != nullptr){
if(tmp1->val != tmp2->val){
return false;
}
tmp1 = tmp1->next;
tmp2 = tmp2->next;
}
return true;
}
};
int main(){
ListNode node1(1);
ListNode node2(1);
node1.next = &node2;
Solution s;
cout<<s.isPalindrome(&node1);
return 0;
}
今天也是爱zz的一天哦!