题解 | #删除链表的节点#

删除链表的节点

https://www.nowcoder.com/practice/f9f78ca89ad643c99701a7142bd59f5d

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
      ListNode* deleteNode1(ListNode* head, int val) {
        if(head==nullptr)
            return head;
        ListNode* res=new ListNode(0);
        res->next=head;
        ListNode* per=res;
        ListNode* cur=head;
        while(cur!=nullptr)
        {

            if(cur->val==val)
            {
                per->next=cur->next;
                break;
            }            
            per=cur;
            cur=cur->next;
        }
        return res->next;
    }
    ListNode* deleteNode(ListNode* head, int val) {
        if(head==nullptr)
            return head;
        ListNode* cur=head->next;
        ListNode* per=new ListNode(0);
        per->next=head;
        while(cur!=nullptr)
        {

            if(cur->val==val)
            {
                head->next=cur->next;
                break;
            }            
            if(head->val==val)
            {
                per->next=per->next->next;
                break;
            }
            head=head->next;
            cur=cur->next;
        }
        return per->next;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务