【LeetCode】30.Linked List — Palindrome Linked List 回文链表

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false

Example 2:

Input: 1->2->2->1
Output: true

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) {
        ListNode* p = head;
        if(head==NULL) return true;
        ListNode* q = head->next;
        if(q==NULL) return true;
        int counter = 0;
        int counter1 = 0;
        while(p!=NULL)  //获取链表长度
        {
            counter++;
            p=p->next;
        }
        p=head;  
        //开始逆置前半段
        counter1=counter/2;
        while(--counter1)     //开始逆置链表前半段
        {
            p->next=q->next;
            q->next=head;
            head=q;
            q=p->next;
        }
        if(counter%2==0)   //链表长度为偶数
        {
            while(q!=NULL)
            {
                if(head->val==q->val)
                {
                    head=head->next;
                    q=q->next;
                    continue;
                }
                else return false;
            }
            return true;
        }
        else     //链表长度为奇数
        {
            q=q->next;
            while(q!=NULL)
            {
                if(head->val==q->val)
                {
                    head=head->next;
                    q=q->next;
                    continue;
                }
                else return false;
            }
            return true;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/hu-19941213/p/11441567.html
今日推荐