您的位置:首页 > 其它

LeetCode 234 Palindrome Linked List题解

2016-11-07 20:45 399 查看
题目地址:https://leetcode.com/problems/palindrome-linked-list/

题目:

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?

要求,O(n)的时间复杂度和O(1)的空间复杂度

1)算法思路

将后半段链表逆置,然后再比较前后半段是否一致,如果一致则是回文序列,否则非回文。例如:ABCDCBA转化为ABCDABC,前后ABC一致,因此是回文。

2)链表的就地逆置

链表的就地逆置有两种常见的方式:1,从前向后逆置  2,从后向前逆置(基于递归思想)

就地逆置的思想和详解见:http://blog.csdn.net/v_xchen_v/article/details/53067448

我这次解题时,采用的是从前向后头插逆置的方法。

3)JAVA代码

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null||head.next==null)
return true;
boolean isPalin=true;
ListNode temp=head;
int len=1;
while(temp.next!=null)
{
len++;
temp=temp.next;
}
int midLen=(len+1)/2;
temp=head;
//令temp为需逆置链表的前一结点
for(int i=0;i<midLen-1;i++)
{
temp=temp.next;
}
reverse(temp);
temp=temp.next;
for(int i=0;i<len/2;i++)
{
if(head.val!=temp.val)
{
isPalin = false;
break;
}
temp=temp.next;
head=head.next;
}
return isPalin;
}
public void reverse(ListNode head)
{
ListNode p,q;
p=head.next;
while(p!=null)
{
q=p;
p=p.next;
q.next=head.next;
head.next=q;
}
}
}


4)C++代码

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode* head) {
if(head==NULL||head->next==NULL)
return true;
ListNode *temp=head;
bool isPalin = true;
int len=1;
while(temp->next!=NULL)
{
len++;
temp=temp->next;
}
temp=head;
//令temp为待逆置链表头的前一结点
for(int i=0;i<(len+1)/2-1;i++)
{
temp=temp->next;
}
converse(temp);
//令temp为逆置链表头
temp=temp->next;
for(int i=0;i<len/2;i++)
{
if(head->val!=temp->val)
{
isPalin = false;
break;
}
head=head->next;
temp=temp->next;
}
return isPalin;
}
void converse(ListNode *head)
{
ListNode *p=NULL,*q=NULL;
p=head->next;
head->next=NULL;
while(p)
{
q=p;
p=p->next;
q->next=head->next;
head->next=q;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: