代码随想录:移除链表元素
简单的链表操作,注意C++中在访问一个实体结构体时,用.来进行元素访问
ListNode head;
head.val = 10;
head.next = nullptr;
在访问一个指针变量时,用→来进行元素访问,如在本题中,题目给的head是一个指针,所以所有的变量访问都用→
/**
* 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) {
head = head->next;
}
ListNode* target = head;
ListNode* last = head;
while (head != NULL && target->next != NULL) {
if (target->next->val == val) {
target->next = target->next->next;
} else {
target = target->next;
}
}
return head;
}
};
标签:head,ListNode,target,val,随想录,next,链表,移除
From: https://www.cnblogs.com/huigugu/p/18553982