链接: li1
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *fast,*slow;
fast=head;
slow=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
break;
}
if(fast==NULL||fast->next==NULL)
return NULL;
struct ListNode*new=head;
int ct=0;;
while(new!=slow)
{
new=new->next;
slow=slow->next;
ct++;
}
return slow;
}
链接: li2
struct Node* copyRandomList(struct Node* head) {
struct Node* cur=head;
if(cur==NULL)
return NULL;
while(cur)
{
struct Node* copy=(struct Node* )malloc(sizeof(struct Node));
copy->val=cur->val;
struct Node* next=cur->next;
cur->next=copy;
copy->next=next;
cur=next;
}
cur=head;
while(cur)
{
struct Node* next=cur->next;
if(cur->random==NULL)
{
next->random=NULL;
}
else
{
next->random=cur->random->next;
}
cur=next->next;
}
struct Node* newhead=head->next;
cur=head;
while(cur->next->next)
{
struct Node* cur2=cur->next;
struct Node*next=cur2->next;
cur2->next=next->next;
cur->next=next;
cur=next;
}
cur->next->next=NULL;
cur->next=NULL;
return newhead;
}