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 3e6a90b

Browse files
committed
Update linked_list.md
删除链表节点
1 parent be8e9bb commit 3e6a90b

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

‎data_structure/linked_list.md‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,70 @@
1616

1717
## 常见题型
1818

19+
### [移除链表元素](https://leetcode.cn/problems/remove-linked-list-elements)
20+
21+
> 给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
22+
23+
```Python
24+
# Definition for singly-linked list.
25+
# class ListNode:
26+
# def __init__(self, val=0, next=None):
27+
# self.val = val
28+
# self.next = next
29+
class Solution:
30+
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
31+
dummy = ListNode()
32+
dummy.next = head
33+
34+
prev, cur = dummy, head
35+
while cur:
36+
if cur.val == val:
37+
cur = cur.next
38+
prev.next = cur
39+
else:
40+
prev = cur
41+
cur = cur.next
42+
return dummy.next
43+
44+
```
45+
46+
更简洁的话可以写成下面这样
47+
```python
48+
class Solution:
49+
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
50+
dummy = ListNode()
51+
dummy.next = head
52+
53+
cur = dummy
54+
while cur.next:
55+
if cur.next.val == val:
56+
cur.next = cur.next.next
57+
else:
58+
cur = cur.next
59+
return dummy.next
60+
```
61+
62+
63+
1964
### [remove-duplicates-from-sorted-list](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/)
2065

2166
> 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
2267
68+
**Python版本**
69+
```python
70+
class Solution:
71+
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
72+
if head is None: return head
73+
cur = head
74+
while cur.next:
75+
if cur.val == cur.next.val:
76+
cur.next = cur.next.next
77+
else:
78+
cur = cur.next
79+
return head
80+
```
81+
82+
**C++版本**
2383
```cpp
2484
ListNode* deleteDuplicates(ListNode* head) {
2585
if(head == nullptr) return head;

0 commit comments

Comments
(0)

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