题目描述
- 请判断一个链表是否为回文链表。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/64c77a0566cfdbd0d70e796917218046.png#pic_center)
解法一:
- 思路:遍历链表获得链表的长度,采用栈后进先出的思想,将链表的前半部分入栈,每个元素出栈判断是否与链表的元素(长度为奇数时需要向后遍历一个)相等。
- 查看LeetCode题解:也可以使用双指针法,先将链表元素置于数组中,使用双指针逐个判断是否为回文,时间复杂度和空间复杂度如该解法相同。
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)
return true;
Stack<Integer> stack = new Stack<>();
ListNode q = head;
int length = ListNodeLength(q);
for(int i=0;i<length/2;i++){
stack.push(head.val);
head=head.next;
}
if(length%2==1){
head=head.next;
}
while(head!=null){
if(head.val!=stack.pop())
return false;
head=head.next;
}
return true;
}
private int ListNodeLength(ListNode q){
int length=0;
while(q!=null){
q=q.next;
length++;
}
return length;
}
}
- 时间复杂度:O(n) - 遍历两次链表
- 空间复杂度:O(n) - 使用栈空间存储链表元素
解法二:快慢指针
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/ebdef1f6638d6b51c147dfd8d7c5eb1c.png#pic_center)
- 上图为LeetCode官网解释,感觉已经很清晰了,就直接扒过来了
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)
return true;
ListNode slow = head;
ListNode fast = head;
while(fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next.next;
}
ListNode re = reverseList(slow);
ListNode temp = re;
while(re!=null){
if(re.val!=head.val)
return false;
re = re.next;
head = head.next;
}
slow = reverseList(temp);
return true;
}
private ListNode reverseList(ListNode head){
if(head==null)
return null;
ListNode pre = null;
while(head!=null){
ListNode temp = head.next;
head.next = pre;
pre = head;
head = temp;
}
return pre;
}
}