Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit f7f7a08

Browse files
committed
[20220829] leetcode study-plan 문제 풀이
1 parent b9ee027 commit f7f7a08

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# https://leetcode.com/problems/linked-list-cycle-ii/
2+
# 142. Linked List Cycle II
3+
4+
from typing import Optional
5+
from common.leetcodeds import ListNode
6+
7+
8+
# Definition for singly-linked list.
9+
# class ListNode:
10+
# def __init__(self, x):
11+
# self.val = x
12+
# self.next = None
13+
14+
class Solution:
15+
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
16+
if head is None:
17+
return None
18+
slow, fast = head, head
19+
cycle = False
20+
21+
while fast is not None and fast.next is not None:
22+
slow = slow.next
23+
fast = fast.next.next
24+
25+
if slow == fast:
26+
cycle = True
27+
break
28+
29+
if not cycle:
30+
return None
31+
32+
while head != slow:
33+
head = head.next
34+
slow = slow.next
35+
return slow
36+
37+
38+
if __name__ == '__main__':
39+
node = ListNode(3)
40+
node.next = ListNode(2)
41+
node.next.next = ListNode(0)
42+
node.next.next.next = ListNode(-4)
43+
node.next.next.next.next = node.next
44+
sol = Solution()
45+
print(sol.detectCycle(node))
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# https://leetcode.com/problems/middle-of-the-linked-list/
2+
# 876. Middle of the Linked List
3+
4+
from typing import Optional
5+
from common.leetcodeds import ListNode
6+
7+
8+
# Definition for singly-linked list.
9+
# class ListNode:
10+
# def __init__(self, x):
11+
# self.val = x
12+
# self.next = None
13+
14+
15+
class Solution:
16+
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
17+
first, second = head, head
18+
19+
if head.next is None:
20+
return head
21+
22+
while second is not None and second.next is not None:
23+
first = first.next
24+
second = second.next.next
25+
26+
return first
27+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /