首页 > 其他 > 详细

[Linked List]Palindrome Linked List

时间:2015-12-12 10:53:37      阅读:106      评论:0      收藏:0      [点我收藏+]
Total Accepted: 29652 Total Submissions: 117516 Difficulty: Easy

 

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:
    ListNode* reverseList(ListNode* head)
    {
        ListNode *p=head,*newHead = NULL,*next=NULL;
        while(p){
            next = p->next;
            p->next = newHead;
            newHead = p;
            p = next;
        }
        return newHead;
    }
    bool isPalindrome(ListNode* head) {
        if(head==NULL || head->next==NULL){
            return true;
        }
        int len = 0;
        ListNode* p = head;
        while(p){
            len++;
            p=p->next;
        }
        int m = len/2;
        p = head;
        while(--m){
            p=p->next;
        }
        ListNode *node = p;
        if(len%2){
            p = p->next->next;
            ListNode *tmp = node->next;
            node->next = NULL;
            delete(tmp);
        }else{
            p = p->next;
            node->next = NULL;
        }
        ListNode *newHead = reverseList(head);
        while(newHead && p){
            if(newHead->val == p->val){
                newHead=newHead->next;
                p = p->next;
            }else{
                return false;
            }
        }
        return true;
       // while()
    }
};

[Linked List]Palindrome Linked List

原文:http://www.cnblogs.com/zengzy/p/5040843.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!