题目链接:LeeCode234回文链表
题目描述:
拿到这道题首先想到的是找中间节点,所以肯定是用快慢指针,然后应该把前面或者后面倒叙再去比。
就想到反转链表这个题,进阶要求说是空间复杂度O(1)所以不能用栈,于是重新想了一下反转链表的做法,这里也是看了一个大神的思路,自己说实话也是半天没绕过来,取自leetcode题解某大神的图,设置两个指针一边遍历一边将指针反过来,于是反转链表的写法就如下
/**
* 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 static ListNode reverseList(ListNode head) {
ListNode pre=head,cur=null;
while(pre!=null){
ListNode temp=pre.next;
pre.next=cur;
cur=pre;
pre=temp;
}
return cur;
}
}
有了反转链表的写法,判断是否回文就将前半段反过来然后判断相等即可
public static boolean isPalindrome(ListNode head) {
ListNode slow=head,fast=head,cur=null;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
//取一个节点暂存slow的下一个,因为稍后会将slow的next变成前一个节点
ListNode temp=slow.next;
//让slow的next指向前面
slow.next=cur;
//把前面的节点更新过来
cur=slow;
//slow=slow.next
slow=temp;
}
//奇数偶数时候会有不同
if(fast!=null)slow=slow.next;
while (cur != null && slow != null) {
if(cur.val!=slow.val)return false;
cur=cur.next;
slow=slow.next;
}
return true;
}