Palindrome Linked List

原创 2015年07月10日 22:34:29

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?

思路:
把链表一分为二,把右边的一半翻转,再逐个比对左右的链表即可。

/**
 * 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||!head->next){
            return true;
        }
        ListNode *p,*pre,*q;
        p=head;
        q=head;
        pre=NULL;
        while(q){
            q=q->next;
            if(!q){
                break;
            }
            pre=p;
            p=p->next;
            q=q->next;
        }
        pre->next=NULL;
        ListNode *r=reverse(p);
        p=head;
        q=r;
        while(p&&q){
            if(p->val!=q->val){
                return false;
            }
            p=p->next;
            q=q->next;
        }
        return true;

    }

    ListNode* reverse(ListNode *head){
        ListNode *h=NULL;
        ListNode *p=head;
        ListNode *tail=NULL;
        while(p){
            ListNode *next=p->next;
            p->next=NULL;
            if(!h){
                h=p;
            }else{
                p->next=h;
                h=p;
            }
            p=next;
        }
        return h;
    }
};
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

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...

Palindrome Linked List

题目地址:https://leetcode.com/problems/palindrome-linked-list/Given a singly linked list, determine if i...

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) tim...

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...

234. Palindrome Linked List

Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

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