[leetcode] 234. Palindrome Linked List 解题报告

来源:互联网 发布:c语言输出水仙花数 编辑:程序博客网 时间:2024/06/16 18:02

题目链接:https://leetcode.com/problems/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(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) {        if(head == NULL || head->next == NULL)            return true;        ListNode *slow = head, *fast = head, *p, *q = head;        while(fast->next && fast->next->next)        {            slow = slow->next;            fast = fast->next->next;        }        p = slow->next;        while(p->next)        {            ListNode *tem = p->next;            p->next = tem->next;            tem->next = slow->next;            slow->next = tem;        }        while(slow->next)        {            slow = slow->next;            if(slow->val != q->val) return false;            q = q->next;          }        return true;    }};

参考:http://www.cnblogs.com/grandyang/p/4635425.html

0 0
原创粉丝点击