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 6402f92

Browse files
author
weiy
committed
remove linked list elements easy
1 parent a2f3e2e commit 6402f92

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

‎Array/RemoveLinkedListElements.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
"""
2+
Remove all elements from a linked list of integers that have value val.
3+
4+
Example:
5+
6+
Input: 1->2->6->3->4->5->6, val = 6
7+
Output: 1->2->3->4->5
8+
9+
删除所有的val。
10+
11+
注意下开头即为 val 的情况。
12+
13+
beat
14+
90%
15+
16+
测试地址:
17+
https://leetcode.com/problems/remove-linked-list-elements/description/
18+
19+
"""
20+
# Definition for singly-linked list.
21+
# class ListNode(object):
22+
# def __init__(self, x):
23+
# self.val = x
24+
# self.next = None
25+
26+
class Solution(object):
27+
def removeElements(self, head, val):
28+
"""
29+
:type head: ListNode
30+
:type val: int
31+
:rtype: ListNode
32+
"""
33+
34+
while head:
35+
if head.val == val:
36+
head = head.next
37+
else:
38+
break
39+
40+
_head = head
41+
42+
if not _head:
43+
return None
44+
45+
while head and head.next:
46+
if head.next.val == val:
47+
head.next = head.next.next
48+
else:
49+
head = head.next
50+
return _head

0 commit comments

Comments
(0)

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