每日一题04

每日一题04

每日一题day4

每日一题

链表定义

cpp

1
2
3
4
5
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x),next(NULL) {}
}

python

1
2
3
4
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next

移除链表元素

https://leetcode.cn/problems/remove-linked-list-elements/

cpp

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head != NULL && head->val == val){
ListNode* temp = head;
head = head-> next;
delete temp;
}
ListNode* cur = head;
while(cur != NULL && cur->next != NULL){
if(cur->next->val == val){
ListNode* temp = cur->next;
cur->next = cur->next->next;
delete temp;
}else{
cur = cur->next;
}
}
return head;
}
};

python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
while head != None and head.val == val:
head = head.next
cur = head
while cur != None and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head

leetcode 707 设计链表

https://leetcode.cn/problems/design-linked-list/

代码:

cpp

1
2
3
4
5
6
```

**python**

```python

作者

Pluto

发布于

2024-07-26

更新于

2026-03-26

许可协议

# 相关文章
  1.每日一题05
  2.每日一题03
  3.每日一题02
  4.每日一题01
评论

:D 一言句子获取中...

加载中,最新评论有1分钟缓存...