回文链表
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
思路:
- 对于原链表我们找到它一半的位置,对后半部分链表进行反转,参考链接1。
- 这个一半的位置需要考虑好。实际上,无论链表长度是奇数或者偶数,取length=(length+1)/2即可。
- 将前半部分链表与反转的链表进行逐节点比较。
代码:
方法1:使用链接1中的方法1进行链表反转。
bool isPalindrome(ListNode* head) {
if(!head || !head->next)
return true;
ListNode* cur_node=head;
//计算链表长度
int length=0;
while(cur_node)
{
length++;
cur_node=cur_node->next;
}
//计算反转的位置
int count=0;
length=(length+1)/2;
cur_node=head;
while(count<length )
{
cur_node=cur_node->next;
count++;
}
//开始反转
ListNode* pre_node=nullptr;
ListNode* next_node=nullptr;
while(cur_node)
{
next_node=cur_node->next;
cur_node->next=pre_node;
pre_node=cur_node;
cur_node=next_node;
}
//开始比较
cur_node=head;
while(pre_node)
{
if(cur_node->val!=pre_node->val)
return false;
cur_node=cur_node->next;
pre_node=pre_node->next;
}
return true;
}
方法2:使用迭代进行反转
//迭代反转
ListNode* reverseList(ListNode* head)
{
if(!head || !head->next)
return head;
auto new_node=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return new_node;
}
//判断回文
bool isPalindrome(ListNode* head) {
if(!head || !head->next)
return true;
ListNode* cur_node=head;
//计算链表长度
int length=0;
while(cur_node)
{
length++;
cur_node=cur_node->next;
}
//计算反转的位置
int count=0;
length=(length+1)/2;
cur_node=head;
while(count<length )
{
cur_node=cur_node->next;
count++;
}
//开始反转
auto new_node=reverseList(cur_node);
//开始比较
cur_node=head;
while(new_node)
{
if(cur_node->val!=new_node->val)
return false;
cur_node=cur_node->next;
new_node=new_node->next;
}
return true;
}
结果:
方法1结果:
方法2结果:
参考链接:
[1] 消失男孩:[LeetCode][C++]反转链表
[2] 以南丶:LeetCode(链表)回文链表(c++)