IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原][LeetCode 第10题] -- Linked List Cycle

    cgl1079743846发表于 2014-12-11 20:57:06
    love 0


    题目链接: linked List Cycle

    题目意思: 给定一个链表,判断链表是否有环


    代码:

    /**
     * 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);
    };
    
    bool Solution::hasCycle (ListNode *head) {
        if (NULL == head) {
            return false;
        }
        ListNode *tmpHeadOne = head;
        ListNode *tmpHeadTwo = head;
        int step = 0;
        while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) {
            if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) {
                return true;
            }
            step++;
            tmpHeadOne = tmpHeadOne->next;
            tmpHeadTwo = tmpHeadTwo->next;
            if (tmpHeadTwo != NULL) {
                tmpHeadTwo = tmpHeadTwo->next;
            }
        }
        return false;
    }
    




沪ICP备19023445号-2号
友情链接