0
点赞
收藏
分享

微信扫一扫

LeetCode 日记 234.回文链表


LeetCode 日记 234.回文链表_链表

思路:先找到两个链表的中间节点,以此为界,分为两个链表,将后半部分链表反转。然后逐个比较两链表的值。不一样,就不接着比较了。比较完将链表恢复原状。

/**
* 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 fast = head,slow = head;
//找到链表的中间结点的前驱
while(fast.next!=null&&fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
//记录前半段链表的尾节点
ListNode end1 = slow;

//反转后半部分链表,将原链表变成两个链表
ListNode head2 = ReverseList(slow.next);
ListNode p1 = head;
ListNode p2 = head2;

boolean result = true;
while(p2!=null){
if(p1.val!=p2.val){
result = false;
break;
}
p1 = p1.next;
p2 = p2.next;
}

//恢复链表
head2 = ReverseList(head2);
end1.next = head2;
return result;

}
//反装链表
public ListNode ReverseList(ListNode head) {
if(head == null){
return null;
}

ListNode pre = null,next = null,cur = head;
while(cur!=null){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}

思路2:还可以借助数组来进行比较。将链表中的值拷贝到一个数组内,然后双指针从头尾比较。


举报

相关推荐

0 条评论