前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >141. Linked List Cycle(Linked List-Easy)

141. Linked List Cycle(Linked List-Easy)

作者头像
Jack_Cui
发布2017-12-28 12:00:34
5210
发布2017-12-28 12:00:34
举报
文章被收录于专栏:Jack-CuiJack-CuiJack-Cui

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

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

题目:判断一个给定的列表,是否成环,也就是,判断是否首尾相连。

思路:创建一个快指针,一个慢指针。快指针一次走两布,慢指针一次走一步。慢指针走一圈,快指针走两圈,如果两个指针指向位置相同了,说明列表是环状的。

Language:c

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode *fast = (struct ListNode *)malloc(sizeof(struct ListNode));
    struct ListNode *slow = (struct ListNode *)malloc(sizeof(struct ListNode));
    fast = head;
    slow = head;
    while(fast != NULL && fast->next != NULL){
        slow = slow->next;
        fast = fast->next->next;
        if(fast == slow){
            return true;
        }
    }
    return false;
}

Language : cpp

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

Language:python

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        try:
            slow = head
            fast = head.next
            while slow is not fast:
                slow = slow.next
                fast = fast.next.next
            return True
        except:
            return False

LeetCode题目汇总: https://github.com/Jack-Cherish/LeetCode

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-02-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档