Article directory
Preface
1. Linked list segmentation
Niuke.com CM11: Linked list segmentation - - - Click here to send
Solution:
Idea map:
Code:
2. Circular linked list I
Likou 141: Ring Linked List - - - Click here to send
Idea map:
Extended questions:
Code:
bool hasCycle(struct ListNode *head) {
struct ListNode*fast=head,*slow=head;
while(fast && fast->next)
{
//slow走一步
slow=slow->next;
//fast走两步
fast=fast->next->next;
//若相等(相遇)则有环,返回true并退出程序
if(fast==slow)
{
return true;
}
}
//否则无环
return false;
}
3. Circular Linked List II
Likou 142: Ring Linked List II- - - Click here to send
Solution:
Idea map:
Code:
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*meet=slow;
while(head != meet)
{
head=head->next;
meet=meet->next;
}
return meet;
}
}
return NULL;
}
4. Palindrome structure of linked list
Niuke.com OR36: Palindrome structure of linked list - - - Click here to send
Idea map:
Code:
struct ListNode*reverseList(struct ListNode*head)
{
struct ListNode*cur=head;
struct ListNode*newhead=NULL;
while(cur)
{
struct ListNode*next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
struct ListNode*middleNode(struct ListNode*head)
{
struct ListNode*slow=head;
struct ListNode*fast=head;
while(fast && fast->next)
{
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
bool chkPalindrome(ListNode* head) {
struct ListNode*mid=middleNode(head);
struct ListNode*rhead=reverseList(mid);
while(head && rhead)
{
if(head->val != rhead->val)
return false;
head=head->next;
rhead=rhead->next;
}
return true;
}
5. Copy of random linked list
Likou 138: Copy of Random Linked List - - - Click here to send
Idea Map:
Code:
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=copy->next;
}
cur=head;
while(cur)
{
struct Node*copy=cur->next;
if(cur->random==NULL)
{
copy->random=NULL;
}
else
{
copy->random=cur->random->next;
}
cur=copy->next;
}
cur=head;
struct Node*newhead=NULL;
struct Node*tail=NULL;
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;
}