可以将链表保存到数组中,然后从两端对数组进行比较,可进行比较
//使用数组
public boolean isPalindrome1(ListNode head) {
if(head==null || head.next==null) {
return true;
}
java.util.ArrayList<Integer> arr = new java.util.ArrayList<Integer>();
//申请一个容器,然后把元素都放到数组中
while(head!=null) {
arr.add(head.val);
head = head.next;
}
int i = 0;
int j = arr.size()-1;
//用i和j两个指针,一个往后,一个往前,不断迭代
//如果i的值不等于j说明不是回文,反之是回文
while(i<j) {
if(arr.get(i).compareTo(arr.get(j))!=0) {
return false;
}
++i;
--j;
}
return true;
}
先找到链表的中间节点
,;将后半部分的链表反转,相当于有两条链表,- 分别进行两条链表的比较
涉及到的知识点
链表的中间节点
链表的反转
这道题比较综合
/**
* 判断链表是否是回文链表
* @param head
* @return
*/
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null) return true;
//获取链表的中间节点
ListNode middle = getMiddle(head);
//将中间节点之后的链表进行翻转
ListNode reverseHead = reverse(middle);
//尚未翻转链表的头部
ListNode temp1 = head;
//已经翻转链表的头部
ListNode temp2 = reverseHead;
//将两个链表从首尾部进行进行比较
while (temp1!=null&&temp2!=null&&temp1!=temp2){
if(temp1.val!=temp2.val) return false;
temp1=temp1.next;
temp2=temp2.next;
}
return true;
}
/**
* 获取链表的中间节点
* @param head
* @return
*/
public ListNode getMiddle(ListNode head){
if(head==null||head.next==null) return head;
ListNode slow = head;
ListNode quick = head;
while (quick!=null&&quick.next!=null){
quick=quick.next.next;
slow=slow.next;
}
return slow;
}
/**
* 翻转以某个节点开头的链表
*/
public ListNode reverse(ListNode head){
if(head==null||head.next==null){
return head;
}
ListNode next = head.next;
ListNode temp = reverse(next);
head.next.next=head;
head.next=null;
return temp;
}