题目描述
方法一:顺序遍历
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if (head == nullptr) {
return nullptr;
}
else if (head-> val == val) {
head = head->next;
return head;
}
ListNode* pre = head;
ListNode* cur = head->next;
while (cur) {
if (cur->val == val) {
pre->next = cur->next;
}
pre = pre->next;
cur = cur->next;
}
return head;
}
};