1 如何建立一个单向链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
2 单链表的逆序
3 找到单链表环开始的地方
方法1:
(1).首先判断是否存在环
(2).若存在环,则从起点开始,每走一步就删除上一个节点的next指针,最后一个节点就是环的起点。因为环的起点会存在两个next指向它
ListNode *detectCycle(ListNode *head) {//每次前进的时候删除上一个指针
if(head==NULL||head->next==NULL)
return NULL;
ListNode*fast=head;
ListNode*slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}
if(fast == NULL||fast->next==NULL)
return NULL;
ListNode * pre=head;
ListNode*cur=head->next;
while(cur!=NULL){
if(pre==cur)
return pre;
pre->next=NULL;
pre=cur;
cur=cur->next;
}
return pre;
}
方法2:
(1)首先判断是否有环,有环时,返回相遇的节点,无环,返回null
(2)有环的情况下, 求链表的入环节点
- fast再次从头出发,每次走一步,
- slow从相遇点出发,每次走一步,
- 再次相遇即为环入口点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL||head->next==NULL)
return NULL;
ListNode*fast=head;
ListNode*slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
break;
}
if(fast == NULL||fast->next==NULL)
return NULL;
fast=head;
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
return slow;
}
};
4 判断一个链表是否有环
class Solution {
public:
bool hasCycle(ListNode *head)
{
if(head==NULL||head->next==NULL)
return false;
ListNode*fast=head;
ListNode*slow=head;
while(fast!=NULL&&fast->next!=NULL){
fast=fast->next->next;
slow=slow->next;
if(fast==slow)
return true;
}
return false;
}
};