每日一题
链表定义
cpp
struct ListNode{
int val;
ListNode *next;
ListNode(int x) : val(x),next(NULL) {}
}
python
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
移除链表元素
https://leetcode.cn/problems/remove-linked-list-elements/
cpp
/**
* 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
# 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
python