给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
示例 1:
输入:head = [1,2,2,1]
输出:true
示例 2:
输入:head = [1,2]
输出:false
提示:
链表中节点数目在范围[1, 105] 内
0 <= Node.val <= 9
进阶:你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
/**
* 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 boolean isPalindrome(ListNode head) {
List<Integer> vals = new ArrayList<Integer>();
// 将链表的值复制到数组中
ListNode currentNode = head;
while (currentNode != null) {
vals.add(currentNode.val);
currentNode = currentNode.next;
}
// 使用双指针判断是否回文
int front = 0;
int back = vals.size() - 1;
while (front < back) {
if (!vals.get(front).equals(vals.get(back))) {
return false;
}
front++;
back--;
}
return true;
}
}O(1)的空间,不考虑链表复原,快慢指针在寻找中间节点的过程中直接反转链表前半部分,找到中间节点之后直接从中间向两边开始比较
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode pre = null;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
ListNode temp = slow.next;
if(pre != null) {
slow.next = pre;
}
pre = slow;
fast = fast.next.next;
slow = temp;
}
if(fast != null) slow = slow.next;
while(slow != null){
if(slow.val != pre.val) return false;
slow = slow.next;
pre = pre.next;
}
return true;
}
}版权声明:本文为qq_38905818原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。