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

判断两种情况。

1.当要删除的结点为开始结点,则返回开始节点的后一个节点。

2.当要删除的结点不是开始结点,则需要把前一个结点的next指针指向要删除结点的后一个结点。

/**
 * 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 head;
        
        ListNode* pre = NULL;
        ListNode* cur = head;
        
        while(cur->val != val) {
            pre = cur;
            cur = cur->next;
        }
        
        if (cur == head) return head->next;
        pre->next = cur->next;
        return head;
        
    }
};
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param val int整型 
# @return ListNode类
#
class Solution:
    def deleteNode(self , head: ListNode, val: int) -> ListNode:
        # write code here
        if head is None: 
            return head
        
        pre = None
        cur = head
        
        while cur.val != val:
            pre = cur
            cur = cur.next
            
        if cur == head:
            return head.next
        
        pre.next = cur.next
        return head
全部评论

相关推荐

06-14 19:09
门头沟学院 Java
darius_:给制造业搞的,什么物料管理生产管理,设备管理点检,最最关键的就是一堆报表看板。个人觉得没啥技术含量都是些基本的crud,但是业务很繁琐那种
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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