本题先将链表的节点值移到数组中,再用双指针去判断该数组是否为回文的即可。 代码如下:
- /**
- * Definition for singly-linked list.
- * struct ListNode {
- * int val;
- * ListNode *next;
- * ListNode() : val(0), next(nullptr) {}
- * ListNode(int x) : val(x), next(nullptr) {}
- * ListNode(int x, ListNode *next) : val(x), next(next) {}
- * };
- */
- class Solution {
- public:
- bool isPalindrome(ListNode* head) {
- vector<int> nums;
- while(head)
- {
- nums.push_back(head->val);
- head = head->next;
- }
- int left = 0;
- int right = nums.size()-1;
- while(left <= right)
- {
- if(nums[left] != nums[right]) return false;
- left++;
- right--;
- }
- return true;
- }
- };
二刷,思路还是先将链表的值放入数组中,判断数组是否回文就简单多了。 java代码如下:
- /**
- * Definition for singly-linked list.
- * public class ListNode {
- * int val;
- * ListNode next;
- * ListNode() {}
- * ListNode(int val) { this.val = val; }
- * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
- * }
- */
- class Solution {
- public boolean isPalindrome(ListNode head) {
- List
nums = new ArrayList<>(); - nums.add(head.val);
- while(head.next != null){
- head = head.next;
- nums.add(head.val);
- }
- for(int i=0; i
- if(nums.get(i) != nums.get(nums.size()-i-1)) return false;
- }
- return true;
- }
- }