码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 线性表 Linked List Cycle

时间:2014-05-15 07:01:57      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   tar   

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

Linked List Cycle

 Total Accepted: 17041 Total Submissions: 48975

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

Follow up:
Can you solve it without using extra space?



题意:判断一个链表中是否有环

思路:快慢指针,如果有环,最终快慢指针会在非NULL相遇

注:用到fast->next前先要确保fast非NULL,要用fast->next->next前先要确保fast,fast->next非NULL

复杂度:时间O(n), 空间O(1)

相关题目:Linked List CycleII

/**
 * 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) {
    	ListNode *fast, *slow;
    	fast = slow = head;
    	while(fast && fast->next){
    		fast = fast->next->next;
    		slow = slow->next;
    		if(fast == slow) return true;
    	}
    	return false;
    }


Leetcode 线性表 Linked List Cycle,布布扣,bubuko.com

Leetcode 线性表 Linked List Cycle

标签:style   blog   class   code   c   tar   

原文地址:http://blog.csdn.net/zhengsenlie/article/details/25721437

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!