141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?
判断是否是存在环,循环链表中尾节点的指针域不再是空,而是指向头节点。
题目要求不要使用extra space,因此,我们就不能保存每一个结点的value,在遍历的时候判断是否是循环。在遍历过程中将每个元素都指向head,这样如果不存在环,就会有空指针,如果存在环,最终会指向head而结束。
方法一:遍历所有节点与头节点比较

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL || head->next==NULL)
            return false;
        ListNode *node=head;
        while(node !=NULL)//判断是否存在空指针
        {
            if(node->next==head)
                return true;
            ListNode *temp=node->next;
            node->next=head;
            node=temp;  //循环判断node
        }
        return false;
    }
};

方法二;设置两个指针遍历,一个步长为1 ,一个步长为2,若有环,这两个指针将会相遇

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL || head->next==NULL)
            return false;
        ListNode *fast=head;
        ListNode *slow=head;
        while(fast && fast->next)
        {
            fast=fast->next->next;
            slow=slow->next;
            if(slow==fast)
                return true;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值