|
16 | 16 |
|
17 | 17 | ## 常见题型
|
18 | 18 |
|
| 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 | + |
19 | 64 | ### [remove-duplicates-from-sorted-list](https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/)
|
20 | 65 |
|
21 | 66 | > 给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
|
22 | 67 |
|
| 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++版本** |
23 | 83 | ```cpp
|
24 | 84 | ListNode* deleteDuplicates(ListNode* head) {
|
25 | 85 | if(head == nullptr) return head;
|
|
0 commit comments