-,1、题目描述
2、题目分析
使用【快慢指针】思路
- 找到前半部分链表的尾节点。
- 反转后半部分链表。
- 判断是否回文。
- 恢复链表。
- 返回结果。
class Solution {
public boolean isPalindrome(ListNode head) {
//链表为空或者只有一个元素,是回文字符串
if(head == null || head.next == null)
return true;
Stack<ListNode> stack = new Stack<ListNode>();
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
stack.push(slow);
slow = slow.next;
fast = fast.next.next;
}
//如果是偶数个元素
if(fast!=null){
stack.push(slow);
}
slow = slow.next;
//开始进行回文数据比较
while(slow != null && !stack.isEmpty()){
ListNode node = stack.pop();
if(node.val != slow.val)
return false;
slow = slow.next;
}
if(slow != null || !stack.isEmpty())
return false;
return true;
}
}
复杂度分析
时间复杂度:O(n),其中 n 指的是链表的大小。
空间复杂度:O(n)。使用了Stack栈辅助空间。
建议可以看官方更好答案,这个写的空间复杂度有些高!