zoukankan      html  css  js  c++  java
  • leetcode-141

    Linked List Cycle

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

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

    此题并不难,声明2个指针一个步长1,一个步长2,互相追逐,如果追上了就说明有循环,就是没有判断链表是否为空卡在那里很多时间。。。不说了。。。

    附上c代码:

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

      

  • 相关阅读:
    本学期3个sprint的团队贡献分
    sprint3个人总结
    12.17第九天
    阶段二总结
    sprint 1 总结
    冲刺一
    课程设计团队信息
    学习进度表
    Sprint3总结
    Res_Orders_02
  • 原文地址:https://www.cnblogs.com/lcbg/p/6537284.html
Copyright © 2011-2022 走看看