class PalindromeList {
public:
bool chkPalindrome(ListNode* A) {
// write code here
ListNode *p = A;
stack<int> s;
while (p)
{
s.push(p->val);
p = p->next;
}
while (A)
{
if (s.top()!= A->val)
{
return false;
}
s.pop();
A = A->next;
}
return true;
}
};
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int la=0;
int lb=0;
ListNode* a=headA;
ListNode* b=headB;
while(a)
{
if (a->next)
{
a = a->next;
}
else
{
break;
}
la++;
}
while(b)
{
if (b->next)
{
b = b->next;
} else
{
break;
}
lb++;
}
a=headA;
b=headB;
if(la>lb)
{
for(int i=0;i<la-lb;i++)
a=a->next;
}
else
{
for(int i=0;i<lb-la;i++)
b=b->next;
}
while(a&&b)
{
if(a==b)
{
return a;
}
a=a->next;
b=b->next;
}
return nullptr;
}
};
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==nullptr)
return false;
ListNode* slow=head->next;
ListNode* quick=head;
while(quick != slow)
{
if(quick == nullptr || slow == nullptr)
return false;
quick = quick->next;
if(quick == slow->next && slow->next == nullptr)
return true;
else if(quick != slow->next && slow->next==nullptr)
return false;
slow = slow->next->next;
}
return true;
}
};
11. 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 NULL OJ链接(类似上一题)
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==nullptr)
return nullptr;
ListNode* slow=head;
ListNode* quick=head;
bool have_cycle=false;
while(quick&&quick->next)
{
quick=quick->next->next;
slow=slow->next;
if(quick&&quick==slow)
{
have_cycle=true;
break;
}
}
if(have_cycle)
{
quick=head;
while(quick!=slow)
{
quick=quick->next;
slow=slow->next;
}
return quick;
}
return nullptr;
}
};
12. 给定一个链表,每个节点包含一个额外增加的随机指针,该指针可以指向链表中的任何节点或空节点。要求返回这个链表的深度拷贝
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head)
return nullptr;
Node* p = head;
while (p)
{
Node* n = new Node(p->val, p->next, nullptr);
Node* c = p->next;
p->next = n;
p = c;
}
p = head;
while (p)
{
if (p->random)
p->next->random = p->random->next;
p = p->next->next;
}
p = head;
Node* ret = head->next;
while (p->next)
{
Node* c = p->next;
p->next = p->next->next;
p = c;
}
return ret;
}
};