码迷,mamicode.com
首页 > 其他好文 > 详细

234. Palindrome Linked List

时间:2017-06-15 12:52:42      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:reverse   val   ica   next   als   this   and   div   pre   

Problem statement

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?

Solution

This is very typical link list problem since it includes two basic and important operations for link list: find middle and reverse the link list.

Generally, we can solve it through three main steps:

  • Find the middle of the link list
  • Reverse the link list from the next of middle
  • Compare head and middle to test if the given link list is a palindrome

Time complexity is O(n), space complexity is 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* mid = find_mid(head);
        mid->next = reverse(mid->next);
        ListNode* start = mid->next;
        mid->next = NULL;
        while(head && start){
            if(head->val != start->val){
                return false;
            }
            head = head->next;
            start = start->next;
        }
        return true;
    }
private:
    ListNode* find_mid(ListNode* head){
        ListNode* fast = head->next;
        ListNode* slow = head;
        while(fast != NULL && fast->next != NULL){
            fast = fast->next->next;
            slow = slow->next;
        }
        return slow;
    }
private:
    ListNode* reverse(ListNode* head){
        ListNode* prev = NULL;
        ListNode* next = NULL;
        while(head){
            next = head->next;
            head->next = prev;
            prev = head;
            head = next;
        }
        return prev;
    }
};

 

234. Palindrome Linked List

标签:reverse   val   ica   next   als   this   and   div   pre   

原文地址:http://www.cnblogs.com/wdw828/p/7016620.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!