请判断一个链表是否为回文链表。
题解:这里用到了头尾双指针,并且把链表的元素复制到了数组中,数组的好处是双指针可以向内索引,终止条件当一个头指针超过尾指针时会终止
#include<algorithm>
#include<vector>
class Solution {
public:
bool isPalindrome(ListNode* head)
{
vector<int>a;
ListNode* p = head;
if(!head||!head->next)
{
return true;
}
while (p)
{
a.push_back(p->val);
p = p->next;
}
int* c;
int* b;
c = &a[0];
b = &a[a.size() - 1];
while (c<b)
{
if (*c != *b)
{
return false;
}
c++;
b--;
}
return true;
}
};
给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
题解:
非常巧妙使用了快慢指针,如果链表没有环,快指针会有可能指向null,这个作为特殊情况,有环的话初始化快指针在慢指针之前,并且快指针相对满指针会快一步,这样在环内快指针就会追上慢指针,从而出循环。
class Solution {
public:
bool hasCycle(ListNode* head)
{
if (!head || !head->next)
{
return false;
}
ListNode* p = head;
ListNode* q = head->next;
while (p != q)
{
if (!q || !q->next)
return false;
p = p->next;
q = q->next->next;
}
return true;
}
};
`
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle