Palindrome Linked List

来源:互联网 发布:阿里云医疗 编辑:程序博客网 时间:2024/06/11 10:43

Question: Given a singly linked list, determine if it is a palindrome. 

验证一个单向链表是否为中心对称链表, 例如: 1 --> 3 --> 4 --> 6 --> 6 --> 4 --> 3 --> 1 (true); 1 --> 3 --> 4 --> 3 --> 1 (true); 2 --> 6 --> 5 --> 4 --> 2 (false)

NoteCould you do it in O(n) time and O(1) space? 时间复杂度: O(n), 空间复杂度: O(1), 即遍历链表一次, 不新建任何链表或其他结构.


Solution: Split linked list into two lists with help of slow and fast pointer. The second half list starts from "slow.next", and then, reverse the second list. If the two lists are same, return true, otherwise, return false.


public class PalindromeLinkedList {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null){
return true;
} else {
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
fast = fast.next.next;
slow = slow.next;
}
ListNode secondHead = slow.next;
slow.next = null;
ListNode p1 = secondHead.next;
ListNode p2 = secondHead;
while(p1 != null){
ListNode temp = p1.next;
p1.next = p2;
p2 = p1;
p1 = temp;
}
secondHead.next = null;

ListNode q = head;
ListNode p = p2;
while(p != null && q != null){
if(p.val != q.val){
return false;
}
p = p.next;
q = q.next;
}
return true;
}
}
}


0 0
原创粉丝点击