Little-Prince

导航

234. 回文链表

234. 回文链表

请判断一个链表是否为回文链表。

示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true

进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
 
思路:
将链表中的值复制到数组中,然后使用双指针法来比较两端的元素,并向中间移动。一个指针从起点向中间移动,另一个指针从终点向中间移动。时间复杂度 o(n),空间复杂度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) {
        ListNode *current;
        if(head==NULL||head->next==NULL)
            return 1;
        vector<int> value;
      
        int size = 0;
        current = head;
        while(current)
        {
            value.push_back(current->val);
            size++;
            current = current->next;
        }
        int middle = size/2;
        int i;
        for(i = 0; i<middle; i++)
        {
            if(value[i] != value[size-1-i])
                return 0;
        }
        return 1;


    }
};

 

 
进阶
思路:
  找到中点,断开链表,翻转后半部分链表,比较前半部分链表和后半部分链表是否一样。时间复杂度 o(n), 空间复杂度 o(1)
  [] [1] [1 0 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, *slow, *tail;
        if(head==NULL||head->next==NULL)
            return 1;
        fast = head->next;
        slow = head;
        while(fast&&fast->next)
        {
            fast = fast->next->next;
            slow = slow->next;
        }

        tail = slow->next;
        slow->next = NULL;
        fast = reverse(tail);
        slow = head;
    
while(fast&&slow) { if(fast->val != slow->val)     return 0;
fast = fast->next; slow = slow->next; } return 1; } ListNode *reverse(ListNode *head) { if(head==NULL||head->next==NULL) return head; ListNode *pre, *current, *temp; current = head; pre = current->next; current->next = NULL; while(pre) { temp = pre->next; pre->next = current; current = pre; pre = temp; } return current; } };

 

 

posted on 2020-07-29 16:56  Little-Prince  阅读(97)  评论(0)    收藏  举报