本文共 1526 字,大约阅读时间需要 5 分钟。
知识点:贪心、指针
时间:2020年10月22日 题目链接:题目
请判断一个链表是否为回文链表。示例 1:
输入: 1->2 输出: false示例 2:
输入: 1->2->2->1 输出: true进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?解法
代码
#include#include 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<
今天也是爱zz的一天哦!
转载地址:http://xmdsn.baihongyu.com/