leetcode-234-Palindrome Linked List

                                      Palindrome Linked List


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?

判断链表是否为回文。

可以反转链表,再判断,请阅 反 转 单 链 表


空间复杂度O(n)。 

/**
 * 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) {
        int a[100000],n=0;
        while (head) {
            a[n++] = head->val;
            head = head->next;
        }
        for (int i=0;i<n/2;i++){
            if (a[i]!=a[n-i-1]) return false;
        }
        return true ;
    }
};


下面的方法,空间复杂度为O(1)


先将链表后半部分反转,判断前一段与后一段链表是否相同。

例如1,2,3,4,3,2,1 后半部分反转后 1,2,3,4,1,2,3

若是回文,则前后部分链表一致

/**
 * 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,*q,*t,*x;
        p = q = head;
        
        // 找到中间的节点 p
        while (q->next&&q->next->next) {
            p = p->next;
            q = q->next->next;
        }
        
        // 反转p后面的链表
        q = p->next;
        x = q->next;
        q->next = NULL;
        while (x) {
            t = x->next;
            x->next = q;
            q = x;
            x = t;
        }
        p->next = q;
        
        // 判断前一段链表 是否和后一段相同 
        while (q) {
            if (head->val != q->val) return false;
            head = head->next;
            q = q->next;
        }
        return true;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值