Palindrome Linked List

来源:互联网 发布:java怎么安装 编辑:程序博客网 时间:2024/06/03 14:50

LeetCode 234. Palindrome Linked List

Description:

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)的时间复杂度和O(1)的空间复杂度。

思路如下:

由于单链表只能沿一个方向遍历,所以不能在头尾设置两个指针进行同时向中遍历,因此根据回文串特性,比较容易想到的思路是将一个单链表从中间分为两部分,后半部分进行单链表反转,反转后与前半部分比较。

代码如下:

/**
 * 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 *fast = head;
        ListNode *slow = head;
        while (fast && fast->next)
        {
            //fast移到末尾,slow移到中间
            fast = fast->next->next;
            slow = slow->next;
        }
        slow = reverse(slow);//反转后半部分
        fast = head;
        while (slow) //一定要用slow,fast不行,因为fast比slow长
        {
            if (slow->val != fast->val)
                return false;
            else
            {
                slow = slow->next;
                fast = fast->next;
            }
        }
        return true;
        
    }
    ListNode* reverse(ListNode *head) {
        ListNode *pre = NULL;
        while (head)
        {
            ListNode *cur = head->next;
            head->next = pre;
            pre = head;
            head = cur;
        }
        return pre;
    }
};


原创粉丝点击