LeetCode 142. Linked List Cycle II

11 篇文章 0 订阅
7 篇文章 0 订阅
  • 描述
    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

  • 思路
    假如允许修改链表,那么倒有一种取巧的办法,即使遍历链表,每次将链表的值赋值为该节点hash,如果有环,那么一定会有一次该节点的hashcode等于该节点的值,返回该节点即得到结果。但是题目中要求不能修改链表,上面的思路就无效,这里参考了其他博主的思路:
    http://blog.csdn.net/xy010902100449/article/details/48995255
  • 符合要求代码(c#)
 public ListNode DetectCycle(ListNode head) {
            if (head == null) return null;
            var fast = head;
            var slow = head;
            do
            {
                if (fast == null) return null;
                fast = fast.next;
                slow = slow.next;
                if (fast != null)
                {
                    fast = fast.next;
                }
                else
                {
                    return null;
                }
            }
            while (fast != slow);
            slow = head;
            while (slow != fast)
            {
                fast = fast.next;
                slow = slow.next;
            }
            return slow;
    }

不符合要求代码(c#)

 public ListNode DetectCycle(ListNode head)
        {

            while (head != null)
            {
                int key = head.GetHashCode();
                if (key == head.val) return head;
                head.val = key;
                head = head.next;
            }
            return null;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值