-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathremove_linked_list_elements.py
More file actions
36 lines (27 loc) ยท 1.35 KB
/
remove_linked_list_elements.py
File metadata and controls
36 lines (27 loc) ยท 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 203. Remove Linked List Elements
# https://leetcode.com/problems/remove-linked-list-elements/
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# ๋งํฌ๋๋ฆฌ์คํธ๊ฐ ์ฃผ์ด์ง ๋ val ์ ํด๋นํ๋ ๊ฐ์ ์ญ์ ํ๋ ๋ฌธ์ ๋ค.
def removeElements(self, head: ListNode, val: int) -> ListNode:
node = head
# ์ฃผ์ด์ง ๋ฆฌ์คํธ ๋
ธ๋๋ฅผ ์ํํ๋ฉด์ ์ฃผ์ด์ง ๊ฐ val ๊ณผ ๋น๊ตํ์ฌ
# ํด๋น val ์ด ๋ฑ์ฅํ๋ฉด ๊ทธ ๋
ธ๋๋ฅผ ์คํตํ๋ ๋ก์ง์ด๋ค. (๋
ธ๋์ ๋ค์-๋ค์ ๋
ธ๋๋ฅผ ๋
ธ๋์ ๋ค์ ๋
ธ๋๋ก ์ฐ๊ฒฐ)
# node์ head๋ฅผ ๋ฐ๋ก ๋๋ ์ด์ ๋ ์ํํ๋ฉด์ ์ด๋ฏธ ํฌ์ธํฐ ๊ฐ ๋์ ๋ค๋ค๋๊ธฐ ๋๋ฌธ์ ์์ ํฌ์ธํฐ๋ฅผ ์ก์์ฃผ๋ ค๊ณ ๊ทธ๋ฐ ๊ฒ์ด๋ค. (์ฃผ์ด์ง ๊ตฌ์กฐ์ฒด์ prev๊ฐ ์์ด์)
while node.next is not None:
if node.next.val == val:
node.next = node.next.next
else:
node = node.next
# node.next ๋ถํฐ ์์ํ์ผ๋ฏ๋ก ์์ ๋
ธ๋๊ฐ val ๊ณผ ๊ฐ์ ๊ฒฝ์ฐ๊ฐ ์์ ์ ์๋ค.
# ๊ด๋ จํ์ฌ ์์ธ์ฒ๋ฆฌ๋ฅผ ํด ์ค๋ค.
return head if head.val != val else head.next
if __name__ == '__main__':
test_cases = """
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
"""