提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
解题过程
解题思路
粗暴做法:用一个列表从头到尾复制链表的数据,再从头和尾两端同时遍历这个列表分辨是否符合回文串的性质,一旦不符合直接返回false。如果最后还是没遇到不符合回文规则的字符,则返回true。
/**
* 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> list = new ArrayList<>();
while(head != null){
list.add(head.val);
head = head.next;
}
for(int i = 0, j = list.size() - 1; i < j; i++, j--){
if(list.get(i) != list.get(j)){
return false;
}
}
return true;
}
}
空间复杂度为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) {
//用快慢指针,把中间节点找出来,然后从中间开始反转后面的,最后比较链表前后两部分是否相等
if(head == null || head.next == null){
return true;
}
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
slow.next = reverseLinkeList(slow.next);
slow = slow.next;
while(slow != null){
if(head.val != slow.val){
return false;
}
slow = slow.next;
head = head.next;
}
return true;
}
public ListNode reverseLinkeList(ListNode node){
ListNode pre = null;
ListNode cur = node;
ListNode next = null;
while(cur != null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}