leetcode 234. 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?

这道题是要判断链表是不是回文链表。

1. 我的做法是先判断链表中间在哪,然后把后半段reverse,在比较前半段和reverse之后的后半段。

/**
 * 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 length = 0;
        for (ListNode * i=head; i!=NULL; i = i -> next )
            length ++;
        ListNode * middle = head;
        if (length % 2 == 0){
            for (int i =0; i < length/2; i++)
                middle = middle -> next;
        }
        else {
            for (int i =0; i < length/2 + 1; i++)
                middle = middle -> next;
        }
        ListNode * tail = reverse (middle);
        for (int i = 0; i < length/2 ; i++){
            if(head -> val != tail -> val) return false;
            head = head -> next;
            tail = tail -> next;
        }
        return true;
    }
    ListNode * reverse (ListNode * head ){
        if (!head || !head -> next) return head;
        ListNode * node = reverse(head->next);
        head -> next -> next = head;
        head -> next = NULL;
        return node;
    }
};

2. 别人的做法用了更加巧妙的递归,基本理解了。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode * temp;
    bool isPalindrome(ListNode* head) {
        temp = head;
        return check(head);
    }
    bool check(ListNode *p){
        if (p == NULL) return true;
        bool ispal = check(p->next) && (temp->val == p->val);
        temp = temp -> next;
        return ispal;
    }
};

有趣的是,两者所用的时间是一样的。

需要注意一下这道题中提到的空间复杂度的问题。需要慢慢研究品味。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值