目录
一、环形链表||
题解1
大体思路为先用快慢指针找相遇点,找到相遇点后用一个指针从链表头走,一个指针从相遇点走,当两指针相遇时,就是环的入口点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
if(fast == slow)
{
struct ListNode* phead = head;
struct ListNode* plist = fast;
while(plist != phead)
{
phead = phead->next;
plist = plist->next;
}
return plist;
}
}
return NULL;
}
题解2
还是先用快慢指针,找到相遇点,存储下此点的下一个点作为头节点,然后让此点指向空作为尾节点,后用链表相交的方法即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode *detectCycle(struct ListNode *head)
{
struct ListNode* fast = head;
struct ListNode* slow = head;
while(fast && fast->next)
{
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
{
struct ListNode* meet = slow;
struct ListNode* meetnext = slow->next;
meet->next = NULL;
struct ListNode* phead = head;
struct ListNode* meetlist = meetnext;
int num1 = 0;
int num2 = 0;
while(phead)
{
phead = phead->next;
num1++;
}
while(meetlist)
{
meetlist = meetlist->next;
num2++;
}
int sub = abs(num1-num2);
struct ListNode* largelist = head;
struct ListNode* lesslist = meetnext;
if(num1 < num2)
{
largelist = meetnext;
lesslist = head;
}
while(sub--)
{
largelist = largelist->next;
}
while(largelist)
{
if(largelist == lesslist)
{
return largelist;
}
largelist = largelist->next;
lesslist = lesslist->next;
}
}
}
return NULL;
}
二、随机链表的复制
题解
思路是先在原链表每个节点后面复制一个相同的节点,这样复制节点的random就是原节点random-->next,再断开复制节点即可。
/**
* Definition for a Node.
* struct Node {
* int val;
* struct Node *next;
* struct Node *random;
* };
*/
struct Node* copyRandomList(struct Node* head)
{
struct Node* phead = head;
while(phead)
{
struct Node* behind = (struct Node*)malloc(sizeof(struct Node));
behind->val = phead->val;
behind->next = phead->next;
phead->next = behind;
phead = phead->next->next;
}
phead = head;
while(phead)
{
struct Node* behind = phead->next;
if(phead->random == NULL)
{
behind->random = NULL;
}
else
{
behind->random = phead->random->next;
}
phead = phead->next->next;
}
phead = head;
struct Node* behind = NULL;
struct Node* ch = NULL;
while(phead && phead->next)
{
if(behind == NULL)
{
ch = behind = phead->next;
}
else
{
phead->next = phead->next->next;
behind->next = behind->next->next;
}
phead = phead->next;
behind = behind->next;
}
return ch;
}