首页 > 其他 > 详细

LeetCode——Linked List Cycle

时间:2016-03-12 10:18:50      阅读:261      评论:0      收藏:0      [点我收藏+]

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

Follow up:

Can you solve it without using extra space?

原题链接:https://oj.leetcode.com/problems/linked-list-cycle/

题目:给定一个链表。推断它是否有环。

继续:

你能不用额外的空间解决吗?

思路:使用两个指针fast,slow,fast每次向前走两步,slow每次向前走一步。假设二者相应的节点相等。即存在环。

	public boolean hasCycle(ListNode head) {
		ListNode fast = head,slow = head;
		if(head == null || head.next == null)
			return false;
		while(fast != null && fast.next != null){
			slow = slow.next;
			fast = fast.next.next;
			if(slow == fast)
				return true;
		}
		return false; 
	}

	// Definition for singly-linked list.
	class ListNode {
		int val;
		ListNode next;

		ListNode(int x) {
			val = x;
			next = null;
		}
	}


LeetCode——Linked List Cycle

原文:http://www.cnblogs.com/mengfanrong/p/5267882.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!