1. 回文链表
public class IsPalindrome234 {
//定义一个单链表
public class ListNode {
int val; //当前节点值
ListNode next; //下一个节点值
//构造方法 初始化当前节点值
ListNode(int x) { val = x; }
}
//方法1:数组 + 双指针 时间复杂度 O(n)
//将链表中的值放入数组中,两个指针分别从首尾出发开始判断值是否相等
public boolean isPalindrome(ListNode head) {
//判断链表是否为空
if(head==null || head.next==null) {
return true;
}
//申请一个容器,然后把元素都放到数组中
List<Integer> arr = new ArrayList<>();
while(head!=null) {
arr.add(head.val);
head = head.next;
}
//用i和j两个指针,一个往后,一个往前,不断迭代
//如果i的值不等于j说明不是回文,反之是回文
int i = 0;
int j = arr.size()-1;
while(i<j) {
//compareTo 两值相等返回0
if(arr.get(i).compareTo(arr.get(j))!=0) {
return false;
}
++i;
--j;
}
return true;
}
//方法2:双指针 + 反转 时间复杂度 O(n)
//用到了链表中的知识:双指针(找链表中间节点) 反转
public boolean isPalindrome02(ListNode head) {
//边界条件不用忘记了
if(head==null || head.next==null) {
return true;
}
ListNode p = new ListNode(-1); //哑元节点
ListNode low = p;
ListNode fast = p;
p.next = head;
//快慢指针不断迭代,找到中间节点
while(fast!=null && fast.next!=null) {
low = low.next;
fast = fast.next.next;
}
ListNode cur = low.next;
ListNode pre = null;
low.next = null;
low = p.next;
//将链表一分为二之后,反转链表后半部分
while(cur!=null) {
ListNode tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
}
//将链表前半部分和 反转的后半部分对比
while(pre!=null) {
if(low.val!=pre.val) {
return false;
}
low = low.next;
pre = pre.next;
}
return true;
}
}
2. LeetCode代码测试