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

删除链表的节点

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

方案一,不添加头结点

包括两种情况:1. 待删除节点位于head结点 2. 待删除节点位于非head节点

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 
     * @param val int整型 
     * @return ListNode类
     */
    ListNode* deleteNode(ListNode* head, int val) {
        // write code here
        if (head == nullptr)
            return nullptr;

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

        ListNode *pNode = head;
        ListNode *pPre = nullptr;
        while (pNode->next != nullptr) {
            pPre = pNode;
            pNode = pNode->next;
            if (pNode->val == val) {
                pPre->next = pNode->next;
                pNode->next = nullptr;
                break;
            }
        }
        return head;
    }
};
全部评论

相关推荐

能干的三文鱼刷了10...:公司可能有弄嵌入式需要会画pcb的需求,而且pcb能快速直观看出一个人某方面的实力。看看是否有面试资格。问你问题也能ai出来,pcb这东西能作假概率不高
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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