标签:palindrome linked li leetcode
描述:
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
思路:
1.如何判断一个链表是否是回文的?很简单将链表中的元素遍历出来并放进ArrayList中,然后可以像数组一样来判断该元素是否为回文的,时间复杂度O(n),空间复杂度O(n),可如何用O(n)的时间复杂度和O(1)的空间复杂度来解决呢?
2.是不是可以考虑 将链表反转?可反转后还是链表啊,要是将链表分为前后两个部分呢,分为两个部分还是无法判断该链表是否为回文链表啊,那要是再将其中一个链表反转一下呢,It‘s done!好多时候,多想一步容易,再多想一步就困难了。
代码:
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)
return true;
ListNode p=head,temp=head,quick=head;
while(temp!=null&&quick!=null)
{
temp=temp.next;
if(quick.next==null)
break;
quick=quick.next.next;
}
temp=reverseList(temp);
p=head;
while(temp!=null&&p!=null)
{
if(temp.val!=p.val)
return false;
temp=temp.next;
p=p.next;
}
return true;
}
public ListNode reverseList(ListNode head)
{
ListNode tempHead=new ListNode(-1);
ListNode p=head.next,q=null;
tempHead.next=head;
head.next=null;
while(p!=null)
{
q=p;
p=p.next;
q.next=tempHead.next;
tempHead.next=q;
}
return tempHead.next;
}版权声明:本文为博主原创文章,未经博主允许不得转载。
leetcode_Palindrome Linked List
标签:palindrome linked li leetcode
原文地址:http://blog.csdn.net/mnmlist/article/details/47605871