题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list
请判断一个链表是否为回文链表。
示例 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) {
if(head == null || head.next == null)
return true;
ListNode pre = head;
ListNode cur = head.next;
pre.next = null;
while(cur != null){
if(cur.val == pre.val && equal(pre,cur)){
return true;
}
if(cur.next != null && cur.next.val == pre.val && equal(pre,cur.next)){
return true;
}
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return false;
}
private boolean equal(ListNode l1,ListNode l2){
while(l1 != null && l2 != null){
if(l1.val == l2.val){
l1 = l1.next;
l2 = l2.next;
}else{
return false;
}
}
return l1==null && l2 == null;
}
}
网友评论