一.题目
请判断一个链表是否为回文链表
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
二.代码(C)
方法一
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
int length(struct ListNode* head);
void cutout(struct ListNode* head,int i);
bool find(struct ListNode* head,int i);
bool isPalindrome(struct ListNode* head)
{
int count;
count = length(head);
if (count==0 || count==1)
return true;
int i;
if (count%2)
{
i=count/2;
cutout(head,i);
}
for(i=count/2;i>0;i--)
{
if (find(head,i))
{
continue;
}
else
return false;
}
return true;
}
bool find(struct ListNode* head,int i)
{
struct ListNode* head1=NULL;
while(i-1)
{
head1 = head;
head = head->next;
i--;
}
if (head->val==head->next->val)
{
if (head->next->next!=NULL)
head1->next=head->next->next;
return true;
}
else
return false;
}
void cutout(struct ListNode* head,int i)
{
while(i-1)
{
head = head->next;
i--;
}
head->next = head->next->next;
}
int length(struct ListNode* head)
{
int count=0;
while(head)
{
count++;
head = head->next;
}
return count;
}
方法二
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool isPalindrome(struct ListNode* head)
{
struct ListNode* slow=head,*fast=head;
struct ListNode* temp=NULL,*temp2;
if(!head ||!head->next)
return true;
do
{
if(!fast->next)
{
fast = slow->next;
slow = temp;
temp = NULL;
}
else if (!fast->next->next)
{
fast = slow->next;
slow->next = temp;
temp = NULL;
}
else
{
fast = fast->next->next;
temp2 = slow->next;
slow->next = temp;
temp = slow;
slow = temp2;
}
}while(temp!=NULL);
while(fast)
{
if (fast->val!=slow->val)
return false;
fast = fast->next;
slow = slow->next;
}
return true;
}
三.提交记录
方法一
方法二
四.备注
方法一:先找到中间位置,逐次前后对比是否等值。
方法二:快慢指针,其中慢指针移动过程中将链表反转,最后对比两个链表的值。