234. Palindrome Linked List【LeetCode】

问题描述

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?

思路一:
把链表里的数存进一个数组里,然后在数组里利用索引判断。

思路二:
利用栈的后进先出原则,把链表后半段的数压栈,一边从栈里pop一边与链表前半段的数判断

但是,前两种方法的空间复杂度均不符合题目要求

思路三:
找到链表中点后,利用快指针fast,慢指针slow,把链表后半段反转,即指针由后指向前一个数,然后两头一起判断,代码如下:

/**
 * 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==NULL || head->next==NULL) return true;
	ListNode *slow = head,*fast = head;
	while(fast->next && fast->next->next)
	{
		slow = slow->next;
		fast = fast->next->next;
	} 
	ListNode *mid = slow->next,*pre=head;
	while(mid->next)
	{
		ListNode *flag = mid->next;
		mid->next= flag->next;
		flag->next =slow->next;
		slow->next=flag;
	}
	while(slow->next)
	{
		slow = slow->next;
		if(pre->val != slow->val)
            return false;
        pre=pre->next;
	}
	return true;
    }
};

猜你喜欢

转载自blog.csdn.net/hhhhhh5863/article/details/88890991