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

删除链表的节点

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

/*class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param head ListNode类 
 * @param val int整型 
 * @return ListNode类
 */
export function deleteNode(head: ListNode, val: number): ListNode {
    // write code here
    //特殊情况,没有头部
    if(!head)return null
    //头部与要删除的节点一样
    if(head.val === val)return head.next
    let h = head
    //其余的要进行遍历迭代
    while(head.next){
        if(head.next.val === val){
             head.next = head.next.next
            break
        }
        //指针往后移动
        head = head.next
    }
    return h
    
}

全部评论

相关推荐

09-25 23:37
已编辑
桂林电子科技大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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