题目
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(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) {
}
}
分析
这道题注意两个点:
- fast和slow找中间点。
- 用stack来存前半段的数据,剩下的就跟中间点之后的数据来比较。
解答
/**
* 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 slow = head;
ListNode fast = head;
Stack<Integer> stack = new Stack<>();
while(fast != null&& fast.next!= null){
stack.push(slow.val);
slow = slow.next;
fast = fast.next.next;
}
if(fast != null){
slow = slow.next;
}
while(slow!= null){
int val = stack.pop();
if(val != slow.val){
return false;
}
slow = slow.next;
}
return true;
}
}