LeetCode----Palindrome Linked List

来源:互联网 发布:艾瑞社交数据研究报告 编辑:程序博客网 时间:2024/04/30 23:34

题目描述:

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==NULL||head->next==NULL) return true;
        ListNode *slow,*fast;
        slow=head;
        fast=head;
        while(fast->next!=NULL&&fast->next->next!=NULL){
            fast=fast->next->next;
            slow=slow->next;
        }
        ListNode *re_head=slow->next;
        slow->next=NULL;
        ListNode *p1,*p2,*p3;
        p1=p2=re_head;
        p3=re_head->next;
        while(p3!=NULL){
            p2=p3;
            p3=p3->next;
            p2->next=p1;
            p1=p2;
        }
        re_head->next=NULL;
        re_head=p2;
        while(re_head!=NULL&&head!=NULL){
            if(re_head->val!=head->val)
            return false;
            re_head=re_head->next;
            head=head->next;
        }
        return true;
    }
};

0 0
原创粉丝点击