题目描述
编写一个函数,检查输入的链表是否是回文的。
示例1
输入: 1->2 输出: false
示例2
输入: 1->2->2->1 输出: true
做题思路
1.借助栈:将链表节点对应的值存进栈中,从头节点开始遍历链表,比较链表的值与出栈时的值是否相等。
2.先找到链表中点,然后反转链表右半部分,比较左半部分和右半部分的对应的值是否相等。
反转链表过程:
代码1(借助栈)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode pre=head;
Stack<Integer> stack=new Stack<>();
//将链表每个节点对应的值存进栈中
while(pre!=null){
stack.push(pre.val);
pre=pre.next;
}
//通过出栈的方式模拟倒着遍历链表
while(head!=null){
if(head.val!=stack.pop()) return false;
head=head.next;
}
return true;
}
}
代码2(反转链表)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
//定义快慢指针找中点,退出循环时slow所指位置即为链表中点
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
//反转右半部分,退出循环时pre所指位置为反转后的右半部分的第一个元素
ListNode pre=null;
while(slow!=null){
ListNode next=slow.next;
slow.next=pre;
pre=slow;
slow=next;
}
//比较左右两段是否一致
while(pre!=null){
if(head.val!=pre.val) return false;
head=head.next;
pre=pre.next;
}
return true;
}
}