环形链表:设置快慢指针解决
带环链表:为节点的next指针指向链表中任意节点
判断是否带环,当快指针追上慢指针,两者相遇即可表示链表为环形链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode*slow=head;
struct ListNode*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
{
return true;
}
}
return false;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode*slow=head;
struct ListNode*fast=head;
while(fast&&fast->next)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow)
{
struct ListNode*meet=slow;
while(meet!=head)
{
meet=meet->next;
head=head->next;
}
return head;
}
}
return NULL;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
int longA=1;
int longB=1;
struct ListNode*curA=headA;
struct ListNode*curB=headB;
while(curA->next)
{
++longA;
curA=curA->next;
}
while(curB->next)
{
++longB;
curB=curB->next;
}
if(curA!=curB)
{
return NULL;
}
int n=abs(longA-longB);
struct ListNode*cur1=headA;
struct ListNode*cur2=headB;
while(n--)
{
if(longA<longB)
{
cur2=cur2->next;
}
else if(longA>longB)
{
cur1=cur1->next;
}
}
while(cur1!=cur2)
{
cur1=cur1->next;
cur2=cur2->next;
}
return cur1;
}
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head) {
struct Node*cur=head;
//创建新节点,链接在原节点后面
while(cur)
{
struct Node*copy=(struct Node*)malloc(sizeof(struct Node));
copy->val=cur->val;
copy->next=cur->next;
cur->next=copy;
cur=cur->next->next;
}
//改变节点的random,排除NULL这种特殊情况
cur=head;
while(cur)
{
struct Node*copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
cur=cur->next->next;
}
//将新节点和旧节点分开,不破坏链表的完整性
struct Node*newhead=NULL,*tail=NULL;
cur=head;
while(cur)
{
struct Node*copy=cur->next;
struct Node*next=copy->next;
if(tail==NULL)
{
newhead=tail=copy;
}
else
{
tail->next=copy;
tail=tail->next;
}
cur->next=next;
cur=next;
}
return newhead;
}