LKJZ18-删除链表节点(双指针)

LKJZ18-删除链表节点

https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/

 

双指针遍历链表

注意特殊情况

要删除的节点是头节点-对头节点重新进行赋值

class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        ListNode*prev=nullptr,*cur=head;
        while(cur!=nullptr){
            if(cur->val!=val){
                prev=cur;
                cur=cur->next;
            }
            else{
                if(cur==head){
                    head=cur->next;
                    cur=head;
                }
                else{
                    prev->next=cur->next;
                    cur=prev->next;
                }
            }
        }
        return head;
    }
};

 

上一篇:算法:合并两个有序链表


下一篇:【数据结构】链表篇