Palindrome Linked List

原创 2016年06月01日 14:46:59
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?

Subscribe to see which companies asked this question

思路:判断一个链表含有的数值是不是一个回文的链表。可以使用快慢指针,找到一个链表的中间节点。将后半部分的链表进行逆序。而后再从head开始进行遍历,一一比对前后两部分的val值是不是相等的。当循环跳出的时候,如果遍历的指针为NULL,则说明整个链表是回文的,否则的话则说明在遍历的过程中遇到了前面部分的val和后面的val不一样的情况,则此时链表不是回文的。

/**
 * 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,*fast=head->next;
        while(fast&&fast->next)
        {
            slow=slow->next;
            fast=fast->next->next;
        }
        //slow后面的位置为链表的后半个部分
        fast=slow->next;
        slow->next=NULL;
        slow=head;
        ListNode *pre=NULL;
        while(fast)
        {
            ListNode *tmp=fast->next;
            fast->next=pre;
            pre=fast;
            fast=tmp;
        }
        while(pre&&slow&&pre->val==slow->val)
        {
            pre=pre->next;
            slow=slow->next;
        }
        return pre?false:true;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Palindrome Linked-List

Given a singly linked list, determine if it is a palindrome. 题目要求能在O(1)的空间和O(n)的时间内完成。基本思路如下: 1. 找到...

57-Palindrome Linked List

Palindrome Linked List My Submissions QuestionEditorial Solution Total Accepted: 46990 Total Subm...

234. Palindrome Linked List(python)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ti...

LeetCode 之 Palindrome Linked List — C++ 实现

Palindrome Linked List   Given a singly linked list, determine if it is a palindrome. Fol...

LeetCode 234: Palindrome Linked List (回文链表)

Given a singly linked list, determine if it is a palindrome.Follow up:Could you do it in O(n) time a...

Leetcode 234. Palindrome Linked List

234. Palindrome Linked List Total Accepted: 69120 Total Submissions: 225579 Difficulty: Easy ...

(LeetCode 234)Palindrome Linked List

Leetcode第234题目是Palindrome Linked List。题目的描述如下: Given a singly linked list, determine if it is a pali...

Palindrome Linked List 判断是否是回文链表

要求O ( n ) 的时间和固定的空间。 数组因为有index可以直接访问,判断是否回文是简单的,那么链表怎么访问到头,尾部呢? 我们的一个想法是:将链表翻转,要是翻转后的链表跟原链表的对应元素值都是...

[LeetCode-234] Palindrome Linked List(回文链表、链表中间节点查找)

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) tim...

234. Palindrome Linked List [easy] (Python)

题目链接https://leetcode.com/problems/palindrome-linked-list/题目原文 Given a singly linked list, determin...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Palindrome Linked List
举报原因:
原因补充:

(最多只允许输入30个字)