【leetcode】234. Palindrome Linked List

来源:互联网 发布:尚学堂 js 编辑:程序博客网 时间:2024/05/29 04:39

一、题目描述

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?


题目解读:判断一个链表是否是回文的


思路:要实现时间复杂度为o(n),空间复杂度为o(1)想了很久,确实不太好实现。后来看了讨论区才发现,原来这么巧妙!

通过一个slow和一个fast指针找到链表的中间位置,然后将后半部的链表进行逆置,最后遍历半个链表,看从左半边链表遍历和从右半边链表的逆置链表遍历是否一致。如果所有节点的值都相等,那么就是回文的。


c++代码(28ms,20.05%)

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool isPalindrome(ListNode* head) {        if(head == NULL || head->next == NULL)            return true;        ListNode* slow=head;        ListNode* fast=head;        while(fast->next!=NULL && fast->next->next!=NULL){            slow=slow->next;            fast=fast->next->next;        }//while        slow->next=reverseList(slow->next);        slow=slow->next;        while(slow){            if(head->val != slow->val)                return false;            head=head->next;            slow=slow->next;        }        return true;    }        ListNode* reverseList(ListNode* root){        ListNode* pre=NULL;        ListNode* next=NULL;        while(root){            next=root->next;            root->next=pre;            pre=root;            root=next;        }        return pre;    }};




0 0