Linked List Cycle
1 bool hasCycle(ListNode *head) { 2 if(head==NULL) 3 return false; 4 ListNode *pBefore,*pLater; 5 if(head->next) 6 pBefore=head->next; 7 else 8 return false; 9 pLater=head; 10 while(pBefore) 11 { 12 if(pBefore->next==pLater) 13 return true; 14 pBefore=pBefore->next; 15 pLater=pLater->next; 16 } 17 return false; 18 }
Status: Time Limit Exceeded
超时,速度一样的话,是不对的,画个图就能很清晰的看出来。
1 bool hasCycle(ListNode *head) { 2 if(head==NULL) 3 return false; 4 if(head->next==NULL) 5 return false; 6 ListNode *pFast,*pSlow; 7 pFast=head->next; 8 pSlow=head; 9 while(pFast&&pSlow){ 10 if(pFast==pSlow) 11 return true; 12 pFast=pFast->next->next; 13 pSlow=pSlow->next; 14 } 15 return false; 16 }
Status: Runtime Error
Last executed input:{1,2}, no cycle
这个又是怎么了???
分析,很不规范的分析,但大体意思是这么着,结合着错误提示看,
slow=1,fast=2
while(1&&2)
fast!=slow
fast=NULL->next;
错了吧,就在这里错的哇
1 bool hasCycle(ListNode *head) { 2 if(head==NULL||head->next==NULL) 3 return false; 4 ListNode *pFast,*pSlow; 5 pFast=head; 6 pSlow=head; 7 while(pFast&&pFast->next){ 8 pSlow=pSlow->next; 9 pFast=pFast->next->next; 10 if(pFast==pSlow) 11 return true; 12 } 13 return false; 14 }
AC
1 bool hasCycle(ListNode *head) { 2 if(head==NULL||head->next==NULL) 3 return false; 4 ListNode *pFast,*pSlow; 5 pFast=head; 6 pSlow=head; 7 while(pFast->next){ 8 pSlow=pSlow->next; 9 pFast=pFast->next->next; 10 if(pFast==pSlow) 11 return true; 12 } 13 return false; 14 }
Status: Runtime Error
Last executed input:{1,2}, no cycle
我只是想省去一个判断信息:pFast&&pFast->next改成pFast->next
结合着错误提示看看
fast=1,slow=1
while(2)
slow=2;
fast=NULL;
while(NULL->next)
又出错了吧
1 public: 2 bool hasCycle(ListNode *head) { 3 if(head->next==NULL) 4 return false; 5 ListNode *pFast,*pSlow; 6 pFast=head; 7 pSlow=head; 8 while(pFast&&pFast->next){ 9 pSlow=pSlow->next; 10 pFast=pFast->next->next; 11 if(pFast==pSlow) 12 return true; 13 } 14 return false; 15 }
第三行我把head==NULL给删了,呵呵,结果就
Submission Result: Runtime Error
Last executed input: | {}, no cycle |
posted on 2014-03-18 17:29 crane_practice 阅读(535) 评论(0) 编辑 收藏 举报