难度简单506
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
先对头结点进行判断,如果给定值在头结点,先进行删除。
链表寻值有一个方法,当不能直接获得节点的前驱时, 可以通过该节点的前一个节点来通过next获得该节点,这样进行删除操作时可以操作。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
while(head != NULL && head->val == val){
ListNode * tmp = head;
head = head->next;
delete tmp;
}
ListNode *cur = head;
while(cur != NULL &&cur->next != NULL){
if(cur->next->val == val){
ListNode *tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}else{
cur = cur->next;
}
}
return head;
}
};
那下面暴力解法为什么就不行呢?!不能AC的原因
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *ha = headA;
ListNode *hb = headB;
while(ha){
while(hb){
if (ha == hb){
return ha;
}
hb = hb->next;
}
ha = ha->next;
}
return nullptr;
}
};