leetcode hot 03
解题思路:找个容器将这个链表遍历一遍存下来,然后再对比;或者用数组列表存下来,双指针前后对比
/**
* 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) {
if(head == null){
return false;
}
ListNode dummy_head = new ListNode();
ListNode p = head;
while(p!=null){
ListNode q = new ListNode(p.val,dummy_head.next);
dummy_head.next = q;
p = p.next;
}
ListNode head1 = dummy_head.next;
while(head1!=null){
if(head1.val!=head.val) return false;
head1 = head1.next;
head = head.next;
}
return true;
}
}
/**
* 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<Integer> list = new ArrayList<>();
while(head!=null){
list.add(head.val);
head = head.next;
}
int left = 0;
int right = list.size()-1;
while(left<right){
if(list.get(left) != list.get(right)) return false;
left++;
right--;
}
return true;
}
}