一、题目描述
请编写一个函数,检查链表是否为回文。
给定一个链表ListNode* pHead,请返回一个bool,代表链表是否为回文。
测试样例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false
二、分析
一开始想到的是反转链表,发现这种方法需要重新为所有的链表节点分配内存,反转完成后再逐个比较。比较麻烦。
1.创建一个list列表,然后遍历链表,将链表中的元素值添加到列表中,然后列表的首部和尾部来逐个的比较两个元素是否相等
2.论坛里有人提出了一种利用栈空间添加前一半的链表元素值,然后比较后一半链表元素的值和栈空间中储存的值是否相等。为了能找到链表的中间位置,创建了一个快指针和一个慢指针,快指针每次移动两个位置,而慢指针每次移动一个位置,这样快指针到达末尾的时候慢指针正好到达了中间位置。(当然需要考虑偶数还是奇数的问题)
3.
三、代码
1.创建list列表的方法
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Palindrome {
public boolean isPalindrome(ListNode pHead) {
// write code here
if(pHead==null)
return false;
List<Integer> list=new ArrayList<Integer>();
while(pHead!=null){
list.add(pHead.val);
pHead=pHead.next;
}
int i=0;
int j=list.size()-1;
while(i<j){
if(list.get(i)!=list.get(j))
return false;
i++;
j--;
}
return true;
/*
ListNode listA=new ListNode(0);
listA.next=pHead;
ListNode listB=new ListNode(0);
ListNode pre =pHead;
ListNode cur=pre.next;
while(cur!=null){
ListNode tmp=cur.next;
cur.next=pre;
}
*/
}
}
2.创建栈空间
if(pHead==null)
return false;
ListNode fast=pHead;
ListNode slow=pHead;
Stack<Integer> stack=new Stack<Integer>();
while(fast!=null && fast.next!=null){
stack.push(slow.val);
slow=slow.next;
fast=fast.next.next;
}
if(fast!=null){//若链表元素个数为奇数,跳过中间元素
slow=slow.next;
}
while(slow!=null){
if(stack.pop()!=slow.val)
return false;
slow=slow.next;
}
return true;