Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
#풀이
문제를 접하고 처음에 든 생각은 '음..head..이론으로는 알겠지만 파이썬으로는 어떻게 사용하지?' ㅎㅎ..
구글에서 조사를 해보니 보통 class를 통해서 head와 tail을 지정하여 객체로 만들어내는걸 알았다.
문제에서도 동일하게 head,next,tail로 변수를 지정해서 각각의 노드와 방향을 알 수 있게 만들어놨다.
이후에 문제의 답을 보고 코드를 만들었는데. while문을 통해 head의 다음 노드를 이동하며 , 모든 노드를 돌게 되었을때 방문했던 노드를 다시 방문하게 된다면 순환하는 linkedlist라고 할 수 있다.
list를 통해서 값을 확인하여 중복값이 많아져서 값이 많이 늘어났는데 다른 사람은 set을 사용해서 방문노드 중복을 막아 시간을 단축한 걸 볼 수 있었다.
class Solution(object):
def hasCycle(self, head):
visit = []
while head :
if head in visit:
return True
visit.append(head)
head = head.next
return False
파이썬에서는 list()를 많이 사용했었지만, 동적리스트와 정적리스트의 차이를 모르고 사용했었다. 최근에 강의를 통해
리스트구조가 어떻게 만들어지는지 알게 되었다.
leetcode문제를 풀면서도 느끼지만, 확실히 기본기부분에서 부족한 부분이 많다는걸 느낀다.
열심히 공부해야지ㅣㅣ..
'알고리즘 > LeetCode' 카테고리의 다른 글
LeetCode 155. Min Stack (0) | 2023.08.31 |
---|---|
LeetCode 35. Search Insert Position (0) | 2023.08.29 |
LeetCode 209. Minimum Size Subarray Sum (0) | 2023.08.29 |
LeetCode 3. Longest Substring Without Repeating Characters (0) | 2023.08.29 |
LeetCode 167. Two Sum II - Input Array Is Sorted (0) | 2023.08.28 |