题目地址:
https://www.lintcode.com/problem/palindrome-linked-list/description
判断链表是否回文。
思路是,先找到链表中点,然后把链表断开后将其中一半翻转,最后判断两个链表是否相等即可(细节上还需要考虑奇偶性的问题)。代码如下:
public class Solution {
/**
* @param head: A ListNode.
* @return: A boolean.
*/
public boolean isPalindrome(ListNode head) {
// write your code here
ListNode dummy = new ListNode(0), slow, fast;
dummy.next = head;
slow = fast = dummy;
// 寻找链表的后半部分的头结点(如果有奇数个节点,则找中间节点的后一个节点)
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode l2 = slow.next;
slow.next = null;
return equal(head, reverse(l2));
}
// 翻转链表
private ListNode reverse(ListNode head) {
ListNode res = null;
while (head != null) {
ListNode tmp = head.next;
head.next = res;
res = head;
head = tmp;
}
return res;
}
// 判断两个链表是否相等(如果其中一个链表比另一个链表多一个节点,则只比较除了多出节点的其余节点)
private boolean equal(ListNode l1, ListNode l2) {
while (l1 != null && l2 != null) {
if (l1.val != l2.val) {
return false;
}
l1 = l1.next;
l2 = l2.next;
}
return true;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 ,空间 。