判断链表中是否有环

  • 实例要求:
  • 给定一个链表的头节点 head ,判断链表中是否有环
  • 如果链表中存在环 ,则返回 true ,否则返回 false;
  • 实例分析:
  • 1、定义两个指针temp1和temp2,指针temp1每次只移动一步,而指针temp2每次移动两步
  • 2、初始化两个指针,指针temp1在位置 head,而指针temp2在位置 head->next
  • 3、在移动的过程中,指针temp2反过来追上指针temp1,就说明该链表为环形链表
  • 示例代码:
c 复制代码
	/**
	 * Definition for singly-linked list.
	 * struct ListNode {
	 *     int val;
	 *     struct ListNode *next;
	 * };
	 */
	bool hasCycle(struct ListNode *head) 
	{
	    if(NULL == head || NULL == head->next)	
	    {
	        return false; 
	    }
	
	    struct ListNode* temp1 = head;
	    struct ListNode* temp2 = head->next;
	
	    while(temp1 != temp2)
	    {
	        if(NULL == temp2 || NULL == temp2->next)
	        {
	            return false;
	        }
	        temp1 = temp1->next;
	        temp2 = temp2->next->next;
	    }
	
	    return true;
	
	    
	}
  • 注意:
  • NULL == head:入参合理性检查;
  • NULL == head->next:只有一个头结点;
相关推荐
杰克尼6 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
xiaolang_8616_wjl7 小时前
c++文字游戏_闯关打怪
开发语言·数据结构·c++·算法·c++20
hqxstudying8 小时前
Java创建型模式---单例模式
java·数据结构·设计模式·代码规范
sun0077008 小时前
数据结构——栈的讲解(超详细)
数据结构
ゞ 正在缓冲99%…12 小时前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
努力写代码的熊大14 小时前
单链表和双向链表
数据结构·链表
Orlando cron15 小时前
数据结构入门:链表
数据结构·算法·链表
许愿与你永世安宁20 小时前
力扣343 整数拆分
数据结构·算法·leetcode
Heartoxx21 小时前
c语言-指针(数组)练习2
c语言·数据结构·算法
杰克尼1 天前
1. 两数之和 (leetcode)
数据结构·算法·leetcode