首页 > 其他 > 详细

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

时间:2019-09-01 12:30:42      阅读:59      评论:0      收藏:0      [点我收藏+]

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;
        }
    }
};

 

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

原文:https://www.cnblogs.com/hu-19941213/p/11441567.html

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