---
# System prepended metadata

title: 思考失敗
tags: [CMD ouput get, 刷題]

---

# 思考失敗

###### tags : `刷題`、`CMD ouput get`


## HackerRank
:::info
判斷一個linked list是否有Cycle exit
:::
![](https://i.imgur.com/crYvPTo.png)
**正解:**
```python=0
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        nodes = set()
        while head:
            if head in nodes:
                #print(head)
                #print(nodes)
                return True
            nodes.add(head)
            head = head.next

        return False
```
**失敗解法:本來是想說在print(head)的過程中，如果head有cycle的話，會output出"Error - Found cycle in the ListNode，只是實作出來的結果是Time Limit Exceeded，猜測是非環的情況print出來花太多時間"**
```python=0
from contextlib import redirect_stdout
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        f = io.StringIO()
        with redirect_stdout(f):
            print(head)
        out = f.getvalue()
        if str(out) == "Error - Found cycle in the ListNode\n":
            return True
        else:
            return False
```