leetcode-234. Palindrome Linked List

来源:互联网 发布:js获取指定网页内容 编辑:程序博客网 时间:2024/05/29 11:20

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?

Subscribe to see which companies asked this question

思路:fast和slow两个指针,fast每次走两步,slow1步,当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;        ListNode* fast = head;        while(fast->next && fast->next->next)        {            slow = slow->next;            fast = fast->next->next;        }        //反转后半部分        slow = reversalList(slow->next);        //slow = slow->next;        while(slow)        {            if(head->val != slow->val)            {                return false;            }            head = head->next;            slow = slow->next;        }        return true;    }    ListNode* reversalList(ListNode* head)    {        ListNode* next = NULL;        ListNode* pre = NULL;        while(head)        {            next = head->next;            head->next = pre;            pre = head;            head = next;        }        return pre;    }};
0 0