遍历法

  • 构建一个新的头节点,使得头节点和非头节点的值删除一样
  • 核心在于front->next=cur->next,因此只要两个节点并保持步长相差一
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param val int整型 
     * @return ListNode类
     */
    ListNode* deleteNode(ListNode* head, int val) {
        // write code here
        
        ListNode* new_head=new ListNode(-1);
        new_head->next=head;
        ListNode* cur=head;
        ListNode* front=new_head;
        while(cur&&cur->val!=val)
        {
            front=cur;
            cur=cur->next;
        }
        if(!cur)
        {
            //cur为空
            return head;
        }
        front->next=cur->next;
        return new_head->next;
    }
};