
难度:Easy
解题思路:先找到链表中间节点,然后切段,然后把后一段翻转,最后对比。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
|
/** * 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%
近期评论