Ideas
数据结构:链表
Code
时间复杂度:O(N),N为链表长度
空间复杂度:O(1)
# 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: ListNode, val: int) -> ListNode:
if not head:
return None
# 因为头节点可能被删除,所以创建哑结点
dummy = ListNode(0, head)
cur = dummy
while(cur.next):
if (cur.next.val == val):
cur.next = cur.next.next
else:
cur = cur.next
return dummy.next
C++
/**
* 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) {
ListNode* dummy = new ListNode(0, head);
ListNode* cur = dummy;
if(head == nullptr) {
return head;
}
while(cur->next) {
if(cur->next->val == val) {
cur->next = cur->next->next;
} else {
cur = cur->next;
}
}
ListNode* ans = dummy->next;
delete dummy;
return ans;
}
};