leetcode_palindrome_linked_list 发表于 2016-12-01 难度:Easy 解题思路:先找到链表中间节点,然后切段,然后把后一段翻转,最后对比。 代码如下: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960/** * 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 *dummy = new ListNode(-1); dummy->next = head; ListNode *slow = dummy; ListNode *fast = dummy; while(fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode *new_head = NULL; if(fast->next != NULL) { new_head = slow->next->next; slow->next = NULL; } else { new_head = slow->next; slow->next = NULL; } new_head = reverseList(new_head); ListNode *first_cur = dummy->next; ListNode *second_cur = new_head; while(first_cur != NULL && second_cur != NULL) { if(first_cur->val != second_cur->val) return false; else { first_cur=first_cur->next; second_cur = second_cur->next; } } return true; } ListNode* reverseList(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while(cur != NULL) { ListNode *ne = cur->next; cur->next = pre; pre = cur; cur = ne; } return pre; }}; 运行结果:23ms,超过56.02%