牛客网刷题----链表

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;
    }
};

5 双向链表的建立与基本操作

https://blog.csdn.net/kelvinmao/article/details/51044928

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值